/* * Copyright (C) 2006 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.graphics.drawable; import android.annotation.ColorInt; import android.annotation.FloatRange; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.Px; import android.compat.annotation.UnsupportedAppUsage; import android.content.pm.ActivityInfo.Config; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.BlendMode; import android.graphics.BlendModeColorFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.DashPathEffect; import android.graphics.Insets; import android.graphics.LinearGradient; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.SweepGradient; import android.graphics.Xfermode; import android.os.Build; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import com.android.internal.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * A Drawable with a color gradient for buttons, backgrounds, etc. * *
It can be defined in an XML file with the <shape>
element. For more
* information, see the guide to Drawable Resources.
[X_radius, Y_radius]
. The corners are
* ordered top-left, top-right, bottom-right, bottom-left. This property
* is honored only when the shape is of type {@link #RECTANGLE}.
*
* Note: changing this property will affect all instances
* of a drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing this property.
*
* @param radii an array of length >= 8 containing 4 pairs of X and Y
* radius for each corner, specified in pixels
*
* @see #mutate()
* @see #setShape(int)
* @see #setCornerRadius(float)
*/
public void setCornerRadii(@Nullable float[] radii) {
mGradientState.setCornerRadii(radii);
mPathIsDirty = true;
invalidateSelf();
}
/**
* Returns the radii for each of the 4 corners. For each corner, the array
* contains 2 values, [X_radius, Y_radius]
. The corners are
* ordered top-left, top-right, bottom-right, bottom-left.
*
* If the radius was previously set with {@link #setCornerRadius(float)}, * or if the corners are not rounded, this method will return {@code null}. * * @return an array containing the radii for each of the 4 corners, or * {@code null} * @see #setCornerRadii(float[]) */ @Nullable public float[] getCornerRadii() { float[] radii = mGradientState.mRadiusArray; if (radii == null) { return null; } return radii.clone(); } /** * Specifies the radius for the corners of the gradient. If this is > 0, * then the drawable is drawn in a round-rectangle, rather than a * rectangle. This property is honored only when the shape is of type * {@link #RECTANGLE}. *
* Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property. * * @param radius The radius in pixels of the corners of the rectangle shape * * @see #mutate() * @see #setCornerRadii(float[]) * @see #setShape(int) */ public void setCornerRadius(float radius) { mGradientState.setCornerRadius(radius); mPathIsDirty = true; invalidateSelf(); } /** * Returns the radius for the corners of the gradient, that was previously set with * {@link #setCornerRadius(float)}. *
* If the radius was previously cleared via passing {@code null} * to {@link #setCornerRadii(float[])}, this method will return 0. * * @return the radius in pixels of the corners of the rectangle shape, or 0 * @see #setCornerRadius */ public float getCornerRadius() { return mGradientState.mRadius; } /** *
Set the stroke width and color for the drawable. If width is zero, * then no stroke is drawn.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param width The width in pixels of the stroke * @param color The color of the stroke * * @see #mutate() * @see #setStroke(int, int, float, float) */ public void setStroke(int width, @ColorInt int color) { setStroke(width, color, 0, 0); } /** *Set the stroke width and color state list for the drawable. If width * is zero, then no stroke is drawn.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param width The width in pixels of the stroke * @param colorStateList The color state list of the stroke * * @see #mutate() * @see #setStroke(int, ColorStateList, float, float) */ public void setStroke(int width, ColorStateList colorStateList) { setStroke(width, colorStateList, 0, 0); } /** *Set the stroke width and color for the drawable. If width is zero, * then no stroke is drawn. This method can also be used to dash the stroke.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param width The width in pixels of the stroke * @param color The color of the stroke * @param dashWidth The length in pixels of the dashes, set to 0 to disable dashes * @param dashGap The gap in pixels between dashes * * @see #mutate() * @see #setStroke(int, int) */ public void setStroke(int width, @ColorInt int color, float dashWidth, float dashGap) { mGradientState.setStroke(width, ColorStateList.valueOf(color), dashWidth, dashGap); setStrokeInternal(width, color, dashWidth, dashGap); } /** *Set the stroke width and color state list for the drawable. If width * is zero, then no stroke is drawn. This method can also be used to dash * the stroke.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param width The width in pixels of the stroke * @param colorStateList The color state list of the stroke * @param dashWidth The length in pixels of the dashes, set to 0 to disable dashes * @param dashGap The gap in pixels between dashes * * @see #mutate() * @see #setStroke(int, ColorStateList) */ public void setStroke( int width, ColorStateList colorStateList, float dashWidth, float dashGap) { mGradientState.setStroke(width, colorStateList, dashWidth, dashGap); final int color; if (colorStateList == null) { color = Color.TRANSPARENT; } else { final int[] stateSet = getState(); color = colorStateList.getColorForState(stateSet, 0); } setStrokeInternal(width, color, dashWidth, dashGap); } private void setStrokeInternal(int width, int color, float dashWidth, float dashGap) { if (mStrokePaint == null) { mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mStrokePaint.setStyle(Paint.Style.STROKE); } mStrokePaint.setStrokeWidth(width); mStrokePaint.setColor(color); DashPathEffect e = null; if (dashWidth > 0) { e = new DashPathEffect(new float[] { dashWidth, dashGap }, 0); } mStrokePaint.setPathEffect(e); mGradientIsDirty = true; invalidateSelf(); } /** *Sets the size of the shape drawn by this drawable.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param width The width of the shape used by this drawable * @param height The height of the shape used by this drawable * * @see #mutate() * @see #setGradientType(int) */ public void setSize(int width, int height) { mGradientState.setSize(width, height); mPathIsDirty = true; invalidateSelf(); } /** *Sets the type of shape used to draw the gradient.
*Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property.
* * @param shape The desired shape for this drawable: {@link #LINE}, * {@link #OVAL}, {@link #RECTANGLE} or {@link #RING} * * @see #mutate() */ public void setShape(@Shape int shape) { mRingPath = null; mPathIsDirty = true; mGradientState.setShape(shape); invalidateSelf(); } /** * Returns the type of shape used by this drawable, one of {@link #LINE}, * {@link #OVAL}, {@link #RECTANGLE} or {@link #RING}. * * @return the type of shape used by this drawable * @see #setShape(int) */ @Shape public int getShape() { return mGradientState.mShape; } /** * Sets the type of gradient used by this drawable. ** Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property. * * @param gradient The type of the gradient: {@link #LINEAR_GRADIENT}, * {@link #RADIAL_GRADIENT} or {@link #SWEEP_GRADIENT} * * @see #mutate() * @see #getGradientType() */ public void setGradientType(@GradientType int gradient) { mGradientState.setGradientType(gradient); mGradientIsDirty = true; invalidateSelf(); } /** * Returns the type of gradient used by this drawable, one of * {@link #LINEAR_GRADIENT}, {@link #RADIAL_GRADIENT}, or * {@link #SWEEP_GRADIENT}. * * @return the type of gradient used by this drawable * @see #setGradientType(int) */ @GradientType public int getGradientType() { return mGradientState.mGradient; } /** * Sets the position of the center of the gradient as a fraction of the * width and height. *
* The default value is (0.5, 0.5). *
* Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property. * * @param x the X-position of the center of the gradient * @param y the Y-position of the center of the gradient * * @see #mutate() * @see #setGradientType(int) * @see #getGradientCenterX() * @see #getGradientCenterY() */ public void setGradientCenter(float x, float y) { mGradientState.setGradientCenter(x, y); mGradientIsDirty = true; invalidateSelf(); } /** * Returns the X-position of the center of the gradient as a fraction of * the width. * * @return the X-position of the center of the gradient * @see #setGradientCenter(float, float) */ public float getGradientCenterX() { return mGradientState.mCenterX; } /** * Returns the Y-position of the center of this gradient as a fraction of * the height. * * @return the Y-position of the center of the gradient * @see #setGradientCenter(float, float) */ public float getGradientCenterY() { return mGradientState.mCenterY; } /** * Sets the radius of the gradient. The radius is honored only when the * gradient type is set to {@link #RADIAL_GRADIENT}. *
* Note: changing this property will affect all instances * of a drawable loaded from a resource. It is recommended to invoke * {@link #mutate()} before changing this property. * * @param gradientRadius the radius of the gradient in pixels * * @see #mutate() * @see #setGradientType(int) * @see #getGradientRadius() */ public void setGradientRadius(float gradientRadius) { mGradientState.setGradientRadius(gradientRadius, TypedValue.COMPLEX_UNIT_PX); mGradientIsDirty = true; invalidateSelf(); } /** * Returns the radius of the gradient in pixels. The radius is valid only * when the gradient type is set to {@link #RADIAL_GRADIENT}. * * @return the radius of the gradient in pixels * @see #setGradientRadius(float) */ public float getGradientRadius() { if (mGradientState.mGradient != RADIAL_GRADIENT) { return 0; } ensureValidRect(); return mGradientRadius; } /** * Sets whether this drawable's {@code level} property will be used to * scale the gradient. If a gradient is not used, this property has no * effect. *
* Scaling behavior varies based on gradient type: *
* The default value for this property is {@code false}. *
* Note: This property corresponds to the
* {@code android:useLevel} attribute on the inner {@code
* Note: Changing this property will affect all instances
* of a drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing this property.
*
* @param useLevel {@code true} if the gradient should be scaled based on
* level, {@code false} otherwise
*
* @see #mutate()
* @see #setLevel(int)
* @see #getLevel()
* @see #getUseLevel()
* @attr ref android.R.styleable#GradientDrawableGradient_useLevel
*/
public void setUseLevel(boolean useLevel) {
mGradientState.mUseLevel = useLevel;
mGradientIsDirty = true;
invalidateSelf();
}
/**
* Returns whether this drawable's {@code level} property will be used to
* scale the gradient.
*
* @return {@code true} if the gradient should be scaled based on level,
* {@code false} otherwise
* @see #setUseLevel(boolean)
* @attr ref android.R.styleable#GradientDrawableGradient_useLevel
*/
public boolean getUseLevel() {
return mGradientState.mUseLevel;
}
private int modulateAlpha(int alpha) {
int scale = mAlpha + (mAlpha >> 7);
return alpha * scale >> 8;
}
/**
* Returns the orientation of the gradient defined in this drawable.
*
* @return the orientation of the gradient defined in this drawable
* @see #setOrientation(Orientation)
*/
public Orientation getOrientation() {
return mGradientState.mOrientation;
}
/**
* Sets the orientation of the gradient defined in this drawable.
*
* Note: changing orientation will affect all instances
* of a drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing the orientation.
*
* @param orientation the desired orientation (angle) of the gradient
*
* @see #mutate()
* @see #getOrientation()
*/
public void setOrientation(Orientation orientation) {
mGradientState.mOrientation = orientation;
mGradientIsDirty = true;
invalidateSelf();
}
/**
* Sets the colors used to draw the gradient.
*
* Each color is specified as an ARGB integer and the array must contain at
* least 2 colors.
*
* Note: changing colors will affect all instances of a
* drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing the colors.
*
* @param colors an array containing 2 or more ARGB colors
* @see #mutate()
* @see #setColor(int)
*/
public void setColors(@Nullable @ColorInt int[] colors) {
setColors(colors, null);
}
/**
* Sets the colors and offsets used to draw the gradient.
*
* Each color is specified as an ARGB integer and the array must contain at
* least 2 colors.
*
* Note: changing colors will affect all instances of a
* drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing the colors.
*
* @param colors an array containing 2 or more ARGB colors
* @param offsets optional array of floating point parameters representing the positions
* of the colors. Null evenly disperses the colors
* @see #mutate()
* @see #setColors(int[])
*/
public void setColors(@Nullable @ColorInt int[] colors, @Nullable float[] offsets) {
mGradientState.setGradientColors(colors);
mGradientState.mPositions = offsets;
mGradientIsDirty = true;
invalidateSelf();
}
/**
* Returns the colors used to draw the gradient, or {@code null} if the
* gradient is drawn using a single color or no colors.
*
* @return the colors used to draw the gradient, or {@code null}
* @see #setColors(int[] colors)
*/
@Nullable
public int[] getColors() {
if (mGradientState.mGradientColors == null) {
return null;
} else {
int[] colors = new int[mGradientState.mGradientColors.length];
for (int i = 0; i < mGradientState.mGradientColors.length; i++) {
if (mGradientState.mGradientColors[i] != null) {
colors[i] = mGradientState.mGradientColors[i].getDefaultColor();
}
}
return colors;
}
}
@Override
public void draw(Canvas canvas) {
if (!ensureValidRect()) {
// nothing to draw
return;
}
// remember the alpha values, in case we temporarily overwrite them
// when we modulate them with mAlpha
final int prevFillAlpha = mFillPaint.getAlpha();
final int prevStrokeAlpha = mStrokePaint != null ? mStrokePaint.getAlpha() : 0;
// compute the modulate alpha values
final int currFillAlpha = modulateAlpha(prevFillAlpha);
final int currStrokeAlpha = modulateAlpha(prevStrokeAlpha);
final boolean haveStroke = currStrokeAlpha > 0 && mStrokePaint != null &&
mStrokePaint.getStrokeWidth() > 0;
final boolean haveFill = currFillAlpha > 0;
final GradientState st = mGradientState;
final ColorFilter colorFilter = mColorFilter != null ? mColorFilter : mBlendModeColorFilter;
/* we need a layer iff we're drawing both a fill and stroke, and the
stroke is non-opaque, and our shapetype actually supports
fill+stroke. Otherwise we can just draw the stroke (if any) on top
of the fill (if any) without worrying about blending artifacts.
*/
final boolean useLayer = haveStroke && haveFill && st.mShape != LINE &&
currStrokeAlpha < 255 && (mAlpha < 255 || colorFilter != null);
/* Drawing with a layer is slower than direct drawing, but it
allows us to apply paint effects like alpha and colorfilter to
the result of multiple separate draws. In our case, if the user
asks for a non-opaque alpha value (via setAlpha), and we're
stroking, then we need to apply the alpha AFTER we've drawn
both the fill and the stroke.
*/
if (useLayer) {
if (mLayerPaint == null) {
mLayerPaint = new Paint();
}
mLayerPaint.setDither(st.mDither);
mLayerPaint.setAlpha(mAlpha);
mLayerPaint.setColorFilter(colorFilter);
float rad = mStrokePaint.getStrokeWidth();
canvas.saveLayer(mRect.left - rad, mRect.top - rad,
mRect.right + rad, mRect.bottom + rad,
mLayerPaint);
// don't perform the filter in our individual paints
// since the layer will do it for us
mFillPaint.setColorFilter(null);
mStrokePaint.setColorFilter(null);
} else {
/* if we're not using a layer, apply the dither/filter to our
individual paints
*/
mFillPaint.setAlpha(currFillAlpha);
mFillPaint.setDither(st.mDither);
mFillPaint.setColorFilter(colorFilter);
if (colorFilter != null && st.mSolidColors == null) {
mFillPaint.setColor(mAlpha << 24);
}
if (haveStroke) {
mStrokePaint.setAlpha(currStrokeAlpha);
mStrokePaint.setDither(st.mDither);
mStrokePaint.setColorFilter(colorFilter);
}
}
switch (st.mShape) {
case RECTANGLE:
if (st.mRadiusArray != null) {
buildPathIfDirty();
canvas.drawPath(mPath, mFillPaint);
if (haveStroke) {
canvas.drawPath(mPath, mStrokePaint);
}
} else if (st.mRadius > 0.0f) {
// since the caller is only giving us 1 value, we will force
// it to be square if the rect is too small in one dimension
// to show it. If we did nothing, Skia would clamp the rad
// independently along each axis, giving us a thin ellipse
// if the rect were very wide but not very tall
float rad = Math.min(st.mRadius,
Math.min(mRect.width(), mRect.height()) * 0.5f);
canvas.drawRoundRect(mRect, rad, rad, mFillPaint);
if (haveStroke) {
canvas.drawRoundRect(mRect, rad, rad, mStrokePaint);
}
} else {
if (mFillPaint.getColor() != 0 || colorFilter != null ||
mFillPaint.getShader() != null) {
canvas.drawRect(mRect, mFillPaint);
}
if (haveStroke) {
canvas.drawRect(mRect, mStrokePaint);
}
}
break;
case OVAL:
canvas.drawOval(mRect, mFillPaint);
if (haveStroke) {
canvas.drawOval(mRect, mStrokePaint);
}
break;
case LINE: {
RectF r = mRect;
float y = r.centerY();
if (haveStroke) {
canvas.drawLine(r.left, y, r.right, y, mStrokePaint);
}
break;
}
case RING:
Path path = buildRing(st);
canvas.drawPath(path, mFillPaint);
if (haveStroke) {
canvas.drawPath(path, mStrokePaint);
}
break;
}
if (useLayer) {
canvas.restore();
} else {
mFillPaint.setAlpha(prevFillAlpha);
if (haveStroke) {
mStrokePaint.setAlpha(prevStrokeAlpha);
}
}
}
/**
* @param mode to draw this drawable with
* @hide
*/
@Override
public void setXfermode(@Nullable Xfermode mode) {
super.setXfermode(mode);
mFillPaint.setXfermode(mode);
}
/**
* @param aa to draw this drawable with
* @hide
*/
public void setAntiAlias(boolean aa) {
mFillPaint.setAntiAlias(aa);
}
private void buildPathIfDirty() {
final GradientState st = mGradientState;
if (mPathIsDirty) {
ensureValidRect();
mPath.reset();
mPath.addRoundRect(mRect, st.mRadiusArray, Path.Direction.CW);
mPathIsDirty = false;
}
}
/**
* Inner radius of the ring expressed as a ratio of the ring's width.
*
* @see #getInnerRadiusRatio()
* @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio
*/
public void setInnerRadiusRatio(
@FloatRange(from = 0.0f, fromInclusive = false) float innerRadiusRatio) {
if (innerRadiusRatio <= 0) {
throw new IllegalArgumentException("Ratio must be greater than zero");
}
mGradientState.mInnerRadiusRatio = innerRadiusRatio;
mPathIsDirty = true;
invalidateSelf();
}
/**
* Return the inner radius of the ring expressed as a ratio of the ring's width.
*
* @see #setInnerRadiusRatio(float)
* @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio
*/
public float getInnerRadiusRatio() {
return mGradientState.mInnerRadiusRatio;
}
/**
* Configure the inner radius of the ring.
*
* @see #getInnerRadius()
* @attr ref android.R.styleable#GradientDrawable_innerRadius
*/
public void setInnerRadius(@Px int innerRadius) {
mGradientState.mInnerRadius = innerRadius;
mPathIsDirty = true;
invalidateSelf();
}
/**
* Return the inner radius of the ring
*
* @see #setInnerRadius(int)
* @attr ref android.R.styleable#GradientDrawable_innerRadius
*/
public @Px int getInnerRadius() {
return mGradientState.mInnerRadius;
}
/**
* Configure the thickness of the ring expressed as a ratio of the ring's width.
*
* @see #getThicknessRatio()
* @attr ref android.R.styleable#GradientDrawable_thicknessRatio
*/
public void setThicknessRatio(
@FloatRange(from = 0.0f, fromInclusive = false) float thicknessRatio) {
if (thicknessRatio <= 0) {
throw new IllegalArgumentException("Ratio must be greater than zero");
}
mGradientState.mThicknessRatio = thicknessRatio;
mPathIsDirty = true;
invalidateSelf();
}
/**
* Return the thickness ratio of the ring expressed as a ratio of the ring's width.
*
* @see #setThicknessRatio(float)
* @attr ref android.R.styleable#GradientDrawable_thicknessRatio
*/
public float getThicknessRatio() {
return mGradientState.mThicknessRatio;
}
/**
* Configure the thickness of the ring.
*
* @attr ref android.R.styleable#GradientDrawable_thickness
*/
public void setThickness(@Px int thickness) {
mGradientState.mThickness = thickness;
mPathIsDirty = true;
invalidateSelf();
}
/**
* Return the thickness of the ring
*
* @see #setThickness(int)
* @attr ref android.R.styleable#GradientDrawable_thickness
*/
public @Px int getThickness() {
return mGradientState.mThickness;
}
/**
* Configure the padding of the gradient shape
* @param left Left padding of the gradient shape
* @param top Top padding of the gradient shape
* @param right Right padding of the gradient shape
* @param bottom Bottom padding of the gradient shape
*
* @attr ref android.R.styleable#GradientDrawablePadding_left
* @attr ref android.R.styleable#GradientDrawablePadding_top
* @attr ref android.R.styleable#GradientDrawablePadding_right
* @attr ref android.R.styleable#GradientDrawablePadding_bottom
*/
public void setPadding(@Px int left, @Px int top, @Px int right, @Px int bottom) {
if (mGradientState.mPadding == null) {
mGradientState.mPadding = new Rect();
}
mGradientState.mPadding.set(left, top, right, bottom);
mPadding = mGradientState.mPadding;
invalidateSelf();
}
private Path buildRing(GradientState st) {
if (mRingPath != null && (!st.mUseLevelForShape || !mPathIsDirty)) return mRingPath;
mPathIsDirty = false;
float sweep = st.mUseLevelForShape ? (360.0f * getLevel() / 10000.0f) : 360f;
RectF bounds = new RectF(mRect);
float x = bounds.width() / 2.0f;
float y = bounds.height() / 2.0f;
float thickness = st.mThickness != -1 ?
st.mThickness : bounds.width() / st.mThicknessRatio;
// inner radius
float radius = st.mInnerRadius != -1 ?
st.mInnerRadius : bounds.width() / st.mInnerRadiusRatio;
RectF innerBounds = new RectF(bounds);
innerBounds.inset(x - radius, y - radius);
bounds = new RectF(innerBounds);
bounds.inset(-thickness, -thickness);
if (mRingPath == null) {
mRingPath = new Path();
} else {
mRingPath.reset();
}
final Path ringPath = mRingPath;
// arcTo treats the sweep angle mod 360, so check for that, since we
// think 360 means draw the entire oval
if (sweep < 360 && sweep > -360) {
ringPath.setFillType(Path.FillType.EVEN_ODD);
// inner top
ringPath.moveTo(x + radius, y);
// outer top
ringPath.lineTo(x + radius + thickness, y);
// outer arc
ringPath.arcTo(bounds, 0.0f, sweep, false);
// inner arc
ringPath.arcTo(innerBounds, sweep, -sweep, false);
ringPath.close();
} else {
// add the entire ovals
ringPath.addOval(bounds, Path.Direction.CW);
ringPath.addOval(innerBounds, Path.Direction.CCW);
}
return ringPath;
}
/**
* Changes this drawable to use a single color instead of a gradient.
*
* Note: changing color will affect all instances of a
* drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing the color.
*
* @param argb The color used to fill the shape
*
* @see #mutate()
* @see #setColors(int[])
* @see #getColor
*/
public void setColor(@ColorInt int argb) {
mGradientState.setSolidColors(ColorStateList.valueOf(argb));
mFillPaint.setColor(argb);
invalidateSelf();
}
/**
* Changes this drawable to use a single color state list instead of a
* gradient. Calling this method with a null argument will clear the color
* and is equivalent to calling {@link #setColor(int)} with the argument
* {@link Color#TRANSPARENT}.
*
* Note: changing color will affect all instances of a
* drawable loaded from a resource. It is recommended to invoke
* {@link #mutate()} before changing the color.
* If the density has been previously set, dispatches the change to
* subclasses so that density-dependent properties may be scaled as
* necessary.
*
* @param targetDensity the new constant state density
*/
public final void setDensity(int targetDensity) {
if (mDensity != targetDensity) {
final int sourceDensity = mDensity;
mDensity = targetDensity;
applyDensityScaling(sourceDensity, targetDensity);
}
}
public boolean hasCenterColor() {
return mGradientColors != null && mGradientColors.length == 3;
}
private void applyDensityScaling(int sourceDensity, int targetDensity) {
if (mInnerRadius > 0) {
mInnerRadius = Drawable.scaleFromDensity(
mInnerRadius, sourceDensity, targetDensity, true);
}
if (mThickness > 0) {
mThickness = Drawable.scaleFromDensity(
mThickness, sourceDensity, targetDensity, true);
}
if (mOpticalInsets != Insets.NONE) {
final int left = Drawable.scaleFromDensity(
mOpticalInsets.left, sourceDensity, targetDensity, true);
final int top = Drawable.scaleFromDensity(
mOpticalInsets.top, sourceDensity, targetDensity, true);
final int right = Drawable.scaleFromDensity(
mOpticalInsets.right, sourceDensity, targetDensity, true);
final int bottom = Drawable.scaleFromDensity(
mOpticalInsets.bottom, sourceDensity, targetDensity, true);
mOpticalInsets = Insets.of(left, top, right, bottom);
}
if (mPadding != null) {
mPadding.left = Drawable.scaleFromDensity(
mPadding.left, sourceDensity, targetDensity, false);
mPadding.top = Drawable.scaleFromDensity(
mPadding.top, sourceDensity, targetDensity, false);
mPadding.right = Drawable.scaleFromDensity(
mPadding.right, sourceDensity, targetDensity, false);
mPadding.bottom = Drawable.scaleFromDensity(
mPadding.bottom, sourceDensity, targetDensity, false);
}
if (mRadius > 0) {
mRadius = Drawable.scaleFromDensity(mRadius, sourceDensity, targetDensity);
}
if (mRadiusArray != null) {
mRadiusArray[0] = Drawable.scaleFromDensity(
(int) mRadiusArray[0], sourceDensity, targetDensity, true);
mRadiusArray[1] = Drawable.scaleFromDensity(
(int) mRadiusArray[1], sourceDensity, targetDensity, true);
mRadiusArray[2] = Drawable.scaleFromDensity(
(int) mRadiusArray[2], sourceDensity, targetDensity, true);
mRadiusArray[3] = Drawable.scaleFromDensity(
(int) mRadiusArray[3], sourceDensity, targetDensity, true);
}
if (mStrokeWidth > 0) {
mStrokeWidth = Drawable.scaleFromDensity(
mStrokeWidth, sourceDensity, targetDensity, true);
}
if (mStrokeDashWidth > 0) {
mStrokeDashWidth = Drawable.scaleFromDensity(
mStrokeDashGap, sourceDensity, targetDensity);
}
if (mStrokeDashGap > 0) {
mStrokeDashGap = Drawable.scaleFromDensity(
mStrokeDashGap, sourceDensity, targetDensity);
}
if (mGradientRadiusType == RADIUS_TYPE_PIXELS) {
mGradientRadius = Drawable.scaleFromDensity(
mGradientRadius, sourceDensity, targetDensity);
}
if (mWidth > 0) {
mWidth = Drawable.scaleFromDensity(mWidth, sourceDensity, targetDensity, true);
}
if (mHeight > 0) {
mHeight = Drawable.scaleFromDensity(mHeight, sourceDensity, targetDensity, true);
}
}
@Override
public boolean canApplyTheme() {
boolean mGradientColorState = mGradientColors != null;
if (mGradientColors != null) {
for (int i = 0; i < mGradientColors.length; i++) {
mGradientColorState |= (mGradientColors[i] != null && mGradientColors[i]
.canApplyTheme());
}
}
return mThemeAttrs != null
|| mAttrSize != null || mAttrGradient != null
|| mAttrSolid != null || mAttrStroke != null
|| mAttrCorners != null || mAttrPadding != null
|| (mTint != null && mTint.canApplyTheme())
|| (mStrokeColors != null && mStrokeColors.canApplyTheme())
|| (mSolidColors != null && mSolidColors.canApplyTheme())
|| mGradientColorState
|| super.canApplyTheme();
}
@Override
public Drawable newDrawable() {
return new GradientDrawable(this, null);
}
@Override
public Drawable newDrawable(@Nullable Resources res) {
// If this drawable is being created for a different density,
// just create a new constant state and call it a day.
final GradientState state;
final int density = Drawable.resolveDensity(res, mDensity);
if (density != mDensity) {
state = new GradientState(this, res);
} else {
state = this;
}
return new GradientDrawable(state, res);
}
@Override
public @Config int getChangingConfigurations() {
return mChangingConfigurations
| (mStrokeColors != null ? mStrokeColors.getChangingConfigurations() : 0)
| (mSolidColors != null ? mSolidColors.getChangingConfigurations() : 0)
| (mTint != null ? mTint.getChangingConfigurations() : 0);
}
public void setShape(@Shape int shape) {
mShape = shape;
computeOpacity();
}
public void setGradientType(@GradientType int gradient) {
mGradient = gradient;
}
public void setGradientCenter(float x, float y) {
mCenterX = x;
mCenterY = y;
}
@NonNull
public Orientation getOrientation() {
return mOrientation;
}
public void setGradientColors(@Nullable int[] colors) {
if (colors == null) {
mGradientColors = null;
} else {
// allocate new CSL array only if the size of the current array is different
// from the size of the given parameter
if (mGradientColors == null || mGradientColors.length != colors.length) {
mGradientColors = new ColorStateList[colors.length];
}
for (int i = 0; i < colors.length; i++) {
mGradientColors[i] = ColorStateList.valueOf(colors[i]);
}
}
mSolidColors = null;
computeOpacity();
}
public void setSolidColors(@Nullable ColorStateList colors) {
mGradientColors = null;
mSolidColors = colors;
computeOpacity();
}
private void computeOpacity() {
mOpaqueOverBounds = false;
mOpaqueOverShape = false;
if (mGradientColors != null) {
for (int i = 0; i < mGradientColors.length; i++) {
if (mGradientColors[i] != null
&& !isOpaque(mGradientColors[i].getDefaultColor())) {
return;
}
}
}
// An unfilled shape is not opaque over bounds or shape
if (mGradientColors == null && mSolidColors == null) {
return;
}
// Colors are opaque, so opaqueOverShape=true,
mOpaqueOverShape = true;
// and opaqueOverBounds=true if shape fills bounds
mOpaqueOverBounds = mShape == RECTANGLE
&& mRadius <= 0
&& mRadiusArray == null;
}
public void setStroke(int width, @Nullable ColorStateList colors, float dashWidth,
float dashGap) {
mStrokeWidth = width;
mStrokeColors = colors;
mStrokeDashWidth = dashWidth;
mStrokeDashGap = dashGap;
computeOpacity();
}
public void setCornerRadius(float radius) {
if (radius < 0) {
radius = 0;
}
mRadius = radius;
mRadiusArray = null;
computeOpacity();
}
public void setCornerRadii(float[] radii) {
mRadiusArray = radii;
if (radii == null) {
mRadius = 0;
}
computeOpacity();
}
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
}
public void setGradientRadius(float gradientRadius, @RadiusType int type) {
mGradientRadius = gradientRadius;
mGradientRadiusType = type;
}
}
static boolean isOpaque(int color) {
return ((color >> 24) & 0xff) == 0xff;
}
/**
* Creates a new themed GradientDrawable based on the specified constant state.
*
* The resulting drawable is guaranteed to have a new constant state.
*
* @param state Constant state from which the drawable inherits
*/
private GradientDrawable(@NonNull GradientState state, @Nullable Resources res) {
mGradientState = state;
updateLocalState(res);
}
private void updateLocalState(Resources res) {
final GradientState state = mGradientState;
if (state.mSolidColors != null) {
final int[] currentState = getState();
final int stateColor = state.mSolidColors.getColorForState(currentState, 0);
mFillPaint.setColor(stateColor);
} else if (state.mGradientColors == null) {
// If we don't have a solid color and we don't have a gradient,
// the app is stroking the shape, set the color to the default
// value of state.mSolidColor
mFillPaint.setColor(0);
} else {
// Otherwise, make sure the fill alpha is maxed out.
mFillPaint.setColor(Color.BLACK);
}
mPadding = state.mPadding;
if (state.mStrokeWidth >= 0) {
mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.setStrokeWidth(state.mStrokeWidth);
if (state.mStrokeColors != null) {
final int[] currentState = getState();
final int strokeStateColor = state.mStrokeColors.getColorForState(
currentState, 0);
mStrokePaint.setColor(strokeStateColor);
}
if (state.mStrokeDashWidth != 0.0f) {
final DashPathEffect e = new DashPathEffect(
new float[] { state.mStrokeDashWidth, state.mStrokeDashGap }, 0);
mStrokePaint.setPathEffect(e);
}
}
mBlendModeColorFilter = updateBlendModeFilter(mBlendModeColorFilter, state.mTint,
state.mBlendMode);
mGradientIsDirty = true;
state.computeOpacity();
}
}
{@code
*