/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package android.support.graphics.drawable;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.DrawableRes;
import android.support.v4.util.ArrayMap;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;
/**
* This lets you create a drawable based on an XML vector graphic. It can be defined in an XML file
* with the <vector> element.
*
* The vector drawable has the following elements:
*
*
<vector>
*
*
Used to define a vector drawable
*
*
android:name
*
Defines the name of this vector drawable.
*
android:width
*
Used to define the intrinsic width of the drawable. This support all the dimension units,
* normally specified with dp.
*
android:height
*
Used to define the intrinsic height the drawable. This support all the dimension units,
* normally specified with dp.
*
android:viewportWidth
*
Used to define the width of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*
android:viewportHeight
*
Used to define the height of the viewport space. Viewport is basically the virtual canvas
* where the paths are drawn on.
*
android:tint
*
The color to apply to the drawable as a tint. By default, no tint is applied.
*
android:tintMode
*
The Porter-Duff blending mode for the tint color. The default value is src_in.
*
android:autoMirrored
*
Indicates if the drawable needs to be mirrored when its layout direction is RTL
* (right-to-left).
*
android:alpha
*
The opacity of this drawable.
*
*
*
*
*
<group>
*
Defines a group of paths or subgroups, plus transformation information. The transformations
* are defined in the same coordinates as the viewport. And the transformations are applied in the
* order of scale, rotate then translate.
*
*
android:name
*
Defines the name of the group.
*
android:rotation
*
The degrees of rotation of the group.
*
android:pivotX
*
The X coordinate of the pivot for the scale and rotation of the group. This is defined in the
* viewport space.
*
android:pivotY
*
The Y coordinate of the pivot for the scale and rotation of the group. This is defined in the
* viewport space.
*
android:scaleX
*
The amount of scale on the X Coordinate.
*
android:scaleY
*
The amount of scale on the Y coordinate.
*
android:translateX
*
The amount of translation on the X coordinate. This is defined in the viewport space.
*
android:translateY
*
The amount of translation on the Y coordinate. This is defined in the viewport space.
*
*
*
*
*
<path>
*
Defines paths to be drawn.
*
*
android:name
*
Defines the name of the path.
*
android:pathData
*
Defines path data using exactly same format as "d" attribute in the SVG's path
* data. This is defined in the viewport space.
*
android:fillColor
*
Defines the color to fill the path (none if not present).
*
android:strokeColor
*
Defines the color to draw the path outline (none if not present).
*
android:strokeWidth
*
The width a path stroke.
*
android:strokeAlpha
*
The opacity of a path stroke.
*
android:fillAlpha
*
The opacity to fill the path with.
*
android:trimPathStart
*
The fraction of the path to trim from the start, in the range from 0 to 1.
*
android:trimPathEnd
*
The fraction of the path to trim from the end, in the range from 0 to 1.
*
android:trimPathOffset
*
Shift trim region (allows showed region to include the start and end), in the range from 0 to
* 1.
*
android:strokeLineCap
*
Sets the linecap for a stroked path: butt, round, square.
*
android:strokeLineJoin
*
Sets the lineJoin for a stroked path: miter,round,bevel.
*
android:strokeMiterLimit
*
Sets the Miter limit for a stroked path.
*
*
*
*
*
<clip-path>
*
Defines path to be the current clip.
*
*
android:name
*
Defines the name of the clip path.
*
android:pathData
*
Defines clip path data using the same format as "d" attribute in the SVG's
* path data.
*
*
*
*
Here is a simple VectorDrawable in this vectordrawable.xml file.
*
*/
public class VectorDrawableCompat extends Drawable {
static final String LOGTAG = "VectorDrawableCompat";
static final PorterDuff.Mode DEFAULT_TINT_MODE = PorterDuff.Mode.SRC_IN;
private static final String SHAPE_CLIP_PATH = "clip-path";
private static final String SHAPE_GROUP = "group";
private static final String SHAPE_PATH = "path";
private static final String SHAPE_VECTOR = "vector";
private static final int LINECAP_BUTT = 0;
private static final int LINECAP_ROUND = 1;
private static final int LINECAP_SQUARE = 2;
private static final int LINEJOIN_MITER = 0;
private static final int LINEJOIN_ROUND = 1;
private static final int LINEJOIN_BEVEL = 2;
private static final boolean DBG_VECTOR_DRAWABLE = true;
private VectorDrawableState mVectorState;
private PorterDuffColorFilter mTintFilter;
private ColorFilter mColorFilter;
private boolean mMutated;
// AnimatedVectorDrawable needs to turn off the cache all the time, otherwise,
// caching the bitmap by default is allowed.
private boolean mAllowCaching = true;
private VectorDrawableCompat() {
mVectorState = new VectorDrawableState();
}
private VectorDrawableCompat(VectorDrawableState state) {
mVectorState = state;
mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
}
@Override
public Drawable mutate() {
if (!mMutated && super.mutate() == this) {
mVectorState = new VectorDrawableState(mVectorState);
mMutated = true;
}
return this;
}
Object getTargetByName(String name) {
return mVectorState.mVPathRenderer.mVGTargetsMap.get(name);
}
@Override
public ConstantState getConstantState() {
mVectorState.mChangingConfigurations = getChangingConfigurations();
return mVectorState;
}
@Override
public void draw(Canvas canvas) {
final Rect bounds = getBounds();
if (bounds.width() == 0 || bounds.height() == 0) {
// too small to draw
return;
}
final int saveCount = canvas.save();
final boolean needMirroring = needMirroring();
canvas.translate(bounds.left, bounds.top);
if (needMirroring) {
canvas.translate(bounds.width(), 0);
canvas.scale(-1.0f, 1.0f);
}
// Color filters always override tint filters.
final ColorFilter colorFilter = mColorFilter == null ? mTintFilter : mColorFilter;
if (!mAllowCaching) {
// AnimatedVectorDrawable
if (!mVectorState.hasTranslucentRoot()) {
mVectorState.mVPathRenderer.draw(
canvas, bounds.width(), bounds.height(), colorFilter);
} else {
mVectorState.createCachedBitmapIfNeeded(bounds);
mVectorState.updateCachedBitmap(bounds);
mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
}
} else {
// Static Vector Drawable case.
mVectorState.createCachedBitmapIfNeeded(bounds);
if (!mVectorState.canReuseCache()) {
mVectorState.updateCachedBitmap(bounds);
mVectorState.updateCacheStates();
}
mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
}
canvas.restoreToCount(saveCount);
}
public int getAlpha() {
return mVectorState.mVPathRenderer.getRootAlpha();
}
@Override
public void setAlpha(int alpha) {
if (mVectorState.mVPathRenderer.getRootAlpha() != alpha) {
mVectorState.mVPathRenderer.setRootAlpha(alpha);
invalidateSelf();
}
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mColorFilter = colorFilter;
invalidateSelf();
}
/**
* Ensures the tint filter is consistent with the current tint color and
* mode.
*/
PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint,
PorterDuff.Mode tintMode) {
if (tint == null || tintMode == null) {
return null;
}
// setMode, setColor of PorterDuffColorFilter are not public method in SDK v7.
// Therefore we create a new one all the time here. Don't expect this is called often.
final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
return new PorterDuffColorFilter(color, tintMode);
}
public void setTint(int tint) {
setTintList(ColorStateList.valueOf(tint));
}
public void setTintList(ColorStateList tint) {
final VectorDrawableState state = mVectorState;
if (state.mTint != tint) {
state.mTint = tint;
mTintFilter = updateTintFilter(mTintFilter, tint, state.mTintMode);
invalidateSelf();
}
}
public void setTintMode(Mode tintMode) {
final VectorDrawableState state = mVectorState;
if (state.mTintMode != tintMode) {
state.mTintMode = tintMode;
mTintFilter = updateTintFilter(mTintFilter, state.mTint, tintMode);
invalidateSelf();
}
}
@Override
public boolean isStateful() {
return super.isStateful() || (mVectorState != null && mVectorState.mTint != null
&& mVectorState.mTint.isStateful());
}
@Override
protected boolean onStateChange(int[] stateSet) {
final VectorDrawableState state = mVectorState;
if (state.mTint != null && state.mTintMode != null) {
// mTintFilter = updateTintFilter(this, mTintFilter, state.mTint, state.mTintMode);
invalidateSelf();
return true;
}
return false;
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public int getIntrinsicWidth() {
return (int) mVectorState.mVPathRenderer.mBaseWidth;
}
@Override
public int getIntrinsicHeight() {
return (int) mVectorState.mVPathRenderer.mBaseHeight;
}
// Don't support re-applying themes. The initial theme loading is working.
public boolean canApplyTheme() {
return false;
}
/**
* The size of a pixel when scaled from the intrinsic dimension to the viewport dimension. This
* is used to calculate the path animation accuracy.
*
* @hide
*/
public float getPixelSize() {
if (mVectorState == null && mVectorState.mVPathRenderer == null ||
mVectorState.mVPathRenderer.mBaseWidth == 0 ||
mVectorState.mVPathRenderer.mBaseHeight == 0 ||
mVectorState.mVPathRenderer.mViewportHeight == 0 ||
mVectorState.mVPathRenderer.mViewportWidth == 0) {
return 1; // fall back to 1:1 pixel mapping.
}
float intrinsicWidth = mVectorState.mVPathRenderer.mBaseWidth;
float intrinsicHeight = mVectorState.mVPathRenderer.mBaseHeight;
float viewportWidth = mVectorState.mVPathRenderer.mViewportWidth;
float viewportHeight = mVectorState.mVPathRenderer.mViewportHeight;
float scaleX = viewportWidth / intrinsicWidth;
float scaleY = viewportHeight / intrinsicHeight;
return Math.min(scaleX, scaleY);
}
/**
* Create a VectorDrawableCompat object.
*
* @param res the resources.
* @param resId the resource ID for VectorDrawableCompat object.
* @param theme the theme of this vector drawable, it can be null.
* @return a new VectorDrawableCompat or null if parsing error is found.
*/
@Nullable
public static VectorDrawableCompat create(@NonNull Resources res, @DrawableRes int resId,
@Nullable Theme theme) {
try {
final XmlPullParser parser = res.getXml(resId);
final AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty loop
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
final VectorDrawableCompat drawable = new VectorDrawableCompat();
drawable.inflate(res, parser, attrs, theme);
return drawable;
} catch (XmlPullParserException e) {
Log.e(LOGTAG, "parser error", e);
} catch (IOException e) {
Log.e(LOGTAG, "parser error", e);
}
return null;
}
private static int applyAlpha(int color, float alpha) {
int alphaBytes = Color.alpha(color);
color &= 0x00FFFFFF;
color |= ((int) (alphaBytes * alpha)) << 24;
return color;
}
/**
* Obtains styled attributes from the theme, if available, or unstyled
* resources if the theme is null.
*/
static TypedArray obtainAttributes(
Resources res, Theme theme, AttributeSet set, int[] attrs) {
if (theme == null) {
return res.obtainAttributes(set, attrs);
}
return theme.obtainStyledAttributes(set, attrs, 0, 0);
}
@Override
public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs)
throws XmlPullParserException, IOException {
inflate(res, parser, attrs, null);
}
public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
throws XmlPullParserException, IOException {
final VectorDrawableState state = mVectorState;
final VPathRenderer pathRenderer = new VPathRenderer();
state.mVPathRenderer = pathRenderer;
final TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawable);
updateStateFromTypedArray(a);
a.recycle();
state.mChangingConfigurations = getChangingConfigurations();
state.mCacheDirty = true;
inflateInternal(res, parser, attrs, theme);
mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
}
private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException {
final VectorDrawableState state = mVectorState;
final VPathRenderer pathRenderer = state.mVPathRenderer;
// Account for any configuration changes.
// state.mChangingConfigurations |= Utils.getChangingConfigurations(a);
final int tintMode = a.getInt(R.styleable.VectorDrawable_tintMode, -1);
// if (tintMode != -1) {
// state.mTintMode = Utils.parseTintMode(tintMode, DEFAULT_TINT_MODE);
// }
final ColorStateList tint = a.getColorStateList(R.styleable.VectorDrawable_tint);
if (tint != null) {
state.mTint = tint;
}
state.mAutoMirrored = a.getBoolean(
R.styleable.VectorDrawable_autoMirrored, state.mAutoMirrored);
pathRenderer.mViewportWidth = a.getFloat(
R.styleable.VectorDrawable_viewportWidth, pathRenderer.mViewportWidth);
pathRenderer.mViewportHeight = a.getFloat(
R.styleable.VectorDrawable_viewportHeight, pathRenderer.mViewportHeight);
if (pathRenderer.mViewportWidth <= 0) {
throw new XmlPullParserException(a.getPositionDescription() +
" tag requires viewportWidth > 0");
} else if (pathRenderer.mViewportHeight <= 0) {
throw new XmlPullParserException(a.getPositionDescription() +
" tag requires viewportHeight > 0");
}
pathRenderer.mBaseWidth = a.getDimension(
R.styleable.VectorDrawable_width, pathRenderer.mBaseWidth);
pathRenderer.mBaseHeight = a.getDimension(
R.styleable.VectorDrawable_height, pathRenderer.mBaseHeight);
if (pathRenderer.mBaseWidth <= 0) {
throw new XmlPullParserException(a.getPositionDescription() +
" tag requires width > 0");
} else if (pathRenderer.mBaseHeight <= 0) {
throw new XmlPullParserException(a.getPositionDescription() +
" tag requires height > 0");
}
final float alphaInFloat = a.getFloat(R.styleable.VectorDrawable_alpha,
pathRenderer.getAlpha());
pathRenderer.setAlpha(alphaInFloat);
final String name = a.getString(R.styleable.VectorDrawable_name);
if (name != null) {
pathRenderer.mRootName = name;
pathRenderer.mVGTargetsMap.put(name, pathRenderer);
}
}
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs,
Theme theme) throws XmlPullParserException, IOException {
final VectorDrawableState state = mVectorState;
final VPathRenderer pathRenderer = state.mVPathRenderer;
boolean noPathTag = true;
// Use a stack to help to build the group tree.
// The top of the stack is always the current group.
final Stack groupStack = new Stack();
groupStack.push(pathRenderer.mRootGroup);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
final String tagName = parser.getName();
final VGroup currentGroup = groupStack.peek();
Log.v(LOGTAG, tagName);
if (SHAPE_PATH.equals(tagName)) {
final VFullPath path = new VFullPath();
path.inflate(res, attrs, theme);
currentGroup.mChildren.add(path);
if (path.getPathName() != null) {
pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
}
noPathTag = false;
state.mChangingConfigurations |= path.mChangingConfigurations;
} else if (SHAPE_CLIP_PATH.equals(tagName)) {
final VClipPath path = new VClipPath();
path.inflate(res, attrs, theme);
currentGroup.mChildren.add(path);
if (path.getPathName() != null) {
pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
}
state.mChangingConfigurations |= path.mChangingConfigurations;
} else if (SHAPE_GROUP.equals(tagName)) {
VGroup newChildGroup = new VGroup();
newChildGroup.inflate(res, attrs, theme);
currentGroup.mChildren.add(newChildGroup);
groupStack.push(newChildGroup);
if (newChildGroup.getGroupName() != null) {
pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(),
newChildGroup);
}
state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
}
} else if (eventType == XmlPullParser.END_TAG) {
final String tagName = parser.getName();
if (SHAPE_GROUP.equals(tagName)) {
groupStack.pop();
}
}
eventType = parser.next();
}
// Print the tree out for debug.
if (DBG_VECTOR_DRAWABLE) {
printGroupTree(pathRenderer.mRootGroup, 0);
}
if (noPathTag) {
final StringBuffer tag = new StringBuffer();
if (tag.length() > 0) {
tag.append(" or ");
}
tag.append(SHAPE_PATH);
throw new XmlPullParserException("no " + tag + " defined");
}
}
private void printGroupTree(VGroup currentGroup, int level) {
String indent = "";
for (int i = 0; i < level; i++) {
indent += " ";
}
// Print the current node
Log.v(LOGTAG, indent + "current group is :" + currentGroup.getGroupName()
+ " rotation is " + currentGroup.mRotate);
Log.v(LOGTAG, indent + "matrix is :" + currentGroup.getLocalMatrix().toString());
// Then print all the children groups
for (int i = 0; i < currentGroup.mChildren.size(); i++) {
Object child = currentGroup.mChildren.get(i);
if (child instanceof VGroup) {
printGroupTree((VGroup) child, level + 1);
}
}
}
void setAllowCaching(boolean allowCaching) {
mAllowCaching = allowCaching;
}
// We don't support RTL auto mirroring since the getLayoutDirection() is for API 17+.
private boolean needMirroring() {
return false;
}
private static class VectorDrawableState extends ConstantState {
int mChangingConfigurations;
VPathRenderer mVPathRenderer;
ColorStateList mTint = null;
Mode mTintMode = DEFAULT_TINT_MODE;
boolean mAutoMirrored;
Bitmap mCachedBitmap;
int[] mCachedThemeAttrs;
ColorStateList mCachedTint;
Mode mCachedTintMode;
int mCachedRootAlpha;
boolean mCachedAutoMirrored;
boolean mCacheDirty;
/** Temporary paint object used to draw cached bitmaps. */
Paint mTempPaint;
// Deep copy for mutate() or implicitly mutate.
public VectorDrawableState(VectorDrawableState copy) {
if (copy != null) {
mChangingConfigurations = copy.mChangingConfigurations;
mVPathRenderer = new VPathRenderer(copy.mVPathRenderer);
if (copy.mVPathRenderer.mFillPaint != null) {
mVPathRenderer.mFillPaint = new Paint(copy.mVPathRenderer.mFillPaint);
}
if (copy.mVPathRenderer.mStrokePaint != null) {
mVPathRenderer.mStrokePaint = new Paint(copy.mVPathRenderer.mStrokePaint);
}
mTint = copy.mTint;
mTintMode = copy.mTintMode;
mAutoMirrored = copy.mAutoMirrored;
}
}
public void drawCachedBitmapWithRootAlpha(Canvas canvas, ColorFilter filter) {
// The bitmap's size is the same as the bounds.
final Paint p = getPaint(filter);
canvas.drawBitmap(mCachedBitmap, 0, 0, p);
}
public boolean hasTranslucentRoot() {
return mVPathRenderer.getRootAlpha() < 255;
}
/**
* @return null when there is no need for alpha paint.
*/
public Paint getPaint(ColorFilter filter) {
if (!hasTranslucentRoot() && filter == null) {
return null;
}
if (mTempPaint == null) {
mTempPaint = new Paint();
mTempPaint.setFilterBitmap(true);
}
mTempPaint.setAlpha(mVPathRenderer.getRootAlpha());
mTempPaint.setColorFilter(filter);
return mTempPaint;
}
public void updateCachedBitmap(Rect bounds) {
mCachedBitmap.eraseColor(Color.TRANSPARENT);
Canvas tmpCanvas = new Canvas(mCachedBitmap);
mVPathRenderer.draw(tmpCanvas, bounds.width(), bounds.height(), null);
}
public void createCachedBitmapIfNeeded(Rect bounds) {
if (mCachedBitmap == null || !canReuseBitmap(bounds.width(),
bounds.height())) {
mCachedBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(),
Bitmap.Config.ARGB_8888);
mCacheDirty = true;
}
}
public boolean canReuseBitmap(int width, int height) {
if (width == mCachedBitmap.getWidth()
&& height == mCachedBitmap.getHeight()) {
return true;
}
return false;
}
public boolean canReuseCache() {
if (!mCacheDirty
&& mCachedTint == mTint
&& mCachedTintMode == mTintMode
&& mCachedAutoMirrored == mAutoMirrored
&& mCachedRootAlpha == mVPathRenderer.getRootAlpha()) {
return true;
}
return false;
}
public void updateCacheStates() {
// Use shallow copy here and shallow comparison in canReuseCache(),
// likely hit cache miss more, but practically not much difference.
mCachedTint = mTint;
mCachedTintMode = mTintMode;
mCachedRootAlpha = mVPathRenderer.getRootAlpha();
mCachedAutoMirrored = mAutoMirrored;
mCacheDirty = false;
}
public VectorDrawableState() {
mVPathRenderer = new VPathRenderer();
}
@Override
public Drawable newDrawable() {
return new VectorDrawableCompat(this);
}
@Override
public Drawable newDrawable(Resources res) {
return new VectorDrawableCompat(this);
}
@Override
public int getChangingConfigurations() {
return mChangingConfigurations;
}
}
private static class VPathRenderer {
/* Right now the internal data structure is organized as a tree.
* Each node can be a group node, or a path.
* A group node can have groups or paths as children, but a path node has
* no children.
* One example can be:
* Root Group
* / | \
* Group Path Group
* / \ |
* Path Path Path
*
*/
// Variables that only used temporarily inside the draw() call, so there
// is no need for deep copying.
private final Path mPath;
private final Path mRenderPath;
private static final Matrix IDENTITY_MATRIX = new Matrix();
private final Matrix mFinalPathMatrix = new Matrix();
private Paint mStrokePaint;
private Paint mFillPaint;
private PathMeasure mPathMeasure;
/////////////////////////////////////////////////////
// Variables below need to be copied (deep copy if applicable) for mutation.
private int mChangingConfigurations;
private final VGroup mRootGroup;
float mBaseWidth = 0;
float mBaseHeight = 0;
float mViewportWidth = 0;
float mViewportHeight = 0;
int mRootAlpha = 0xFF;
String mRootName = null;
final ArrayMap mVGTargetsMap = new ArrayMap();
public VPathRenderer() {
mRootGroup = new VGroup();
mPath = new Path();
mRenderPath = new Path();
}
public void setRootAlpha(int alpha) {
mRootAlpha = alpha;
}
public int getRootAlpha() {
return mRootAlpha;
}
// setAlpha() and getAlpha() are used mostly for animation purpose, since
// Animator like to use alpha from 0 to 1.
public void setAlpha(float alpha) {
setRootAlpha((int) (alpha * 255));
}
@SuppressWarnings("unused")
public float getAlpha() {
return getRootAlpha() / 255.0f;
}
public VPathRenderer(VPathRenderer copy) {
mRootGroup = new VGroup(copy.mRootGroup, mVGTargetsMap);
mPath = new Path(copy.mPath);
mRenderPath = new Path(copy.mRenderPath);
mBaseWidth = copy.mBaseWidth;
mBaseHeight = copy.mBaseHeight;
mViewportWidth = copy.mViewportWidth;
mViewportHeight = copy.mViewportHeight;
mChangingConfigurations = copy.mChangingConfigurations;
mRootAlpha = copy.mRootAlpha;
mRootName = copy.mRootName;
if (copy.mRootName != null) {
mVGTargetsMap.put(copy.mRootName, this);
}
}
private void drawGroupTree(VGroup currentGroup, Matrix currentMatrix,
Canvas canvas, int w, int h, ColorFilter filter) {
// Calculate current group's matrix by preConcat the parent's and
// and the current one on the top of the stack.
// Basically the Mfinal = Mviewport * M0 * M1 * M2;
// Mi the local matrix at level i of the group tree.
currentGroup.mStackedMatrix.set(currentMatrix);
currentGroup.mStackedMatrix.preConcat(currentGroup.mLocalMatrix);
// Draw the group tree in the same order as the XML file.
for (int i = 0; i < currentGroup.mChildren.size(); i++) {
Object child = currentGroup.mChildren.get(i);
if (child instanceof VGroup) {
VGroup childGroup = (VGroup) child;
drawGroupTree(childGroup, currentGroup.mStackedMatrix,
canvas, w, h, filter);
} else if (child instanceof VPath) {
VPath childPath = (VPath) child;
drawPath(currentGroup, childPath, canvas, w, h, filter);
}
}
}
public void draw(Canvas canvas, int w, int h, ColorFilter filter) {
// Travese the tree in pre-order to draw.
drawGroupTree(mRootGroup, IDENTITY_MATRIX, canvas, w, h, filter);
}
private void drawPath(VGroup vGroup, VPath vPath, Canvas canvas, int w, int h,
ColorFilter filter) {
final float scaleX = w / mViewportWidth;
final float scaleY = h / mViewportHeight;
final float minScale = Math.min(scaleX, scaleY);
mFinalPathMatrix.set(vGroup.mStackedMatrix);
mFinalPathMatrix.postScale(scaleX, scaleY);
vPath.toPath(mPath);
final Path path = mPath;
mRenderPath.reset();
if (vPath.isClipPath()) {
mRenderPath.addPath(path, mFinalPathMatrix);
canvas.clipPath(mRenderPath, Region.Op.REPLACE);
} else {
VFullPath fullPath = (VFullPath) vPath;
if (fullPath.mTrimPathStart != 0.0f || fullPath.mTrimPathEnd != 1.0f) {
float start = (fullPath.mTrimPathStart + fullPath.mTrimPathOffset) % 1.0f;
float end = (fullPath.mTrimPathEnd + fullPath.mTrimPathOffset) % 1.0f;
if (mPathMeasure == null) {
mPathMeasure = new PathMeasure();
}
mPathMeasure.setPath(mPath, false);
float len = mPathMeasure.getLength();
start = start * len;
end = end * len;
path.reset();
if (start > end) {
mPathMeasure.getSegment(start, len, path, true);
mPathMeasure.getSegment(0f, end, path, true);
} else {
mPathMeasure.getSegment(start, end, path, true);
}
path.rLineTo(0, 0); // fix bug in measure
}
mRenderPath.addPath(path, mFinalPathMatrix);
if (fullPath.mFillColor != Color.TRANSPARENT) {
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
final Paint fillPaint = mFillPaint;
fillPaint.setColor(applyAlpha(fullPath.mFillColor, fullPath.mFillAlpha));
fillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, fillPaint);
}
if (fullPath.mStrokeColor != Color.TRANSPARENT) {
if (mStrokePaint == null) {
mStrokePaint = new Paint();
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setAntiAlias(true);
}
final Paint strokePaint = mStrokePaint;
if (fullPath.mStrokeLineJoin != null) {
strokePaint.setStrokeJoin(fullPath.mStrokeLineJoin);
}
if (fullPath.mStrokeLineCap != null) {
strokePaint.setStrokeCap(fullPath.mStrokeLineCap);
}
strokePaint.setStrokeMiter(fullPath.mStrokeMiterlimit);
strokePaint.setColor(applyAlpha(fullPath.mStrokeColor, fullPath.mStrokeAlpha));
strokePaint.setColorFilter(filter);
strokePaint.setStrokeWidth(fullPath.mStrokeWidth * minScale);
canvas.drawPath(mRenderPath, strokePaint);
}
}
}
}
private static class VGroup {
// mStackedMatrix is only used temporarily when drawing, it combines all
// the parents' local matrices with the current one.
private final Matrix mStackedMatrix = new Matrix();
/////////////////////////////////////////////////////
// Variables below need to be copied (deep copy if applicable) for mutation.
final ArrayList