下面列出了怎么用android.graphics.drawable.GradientDrawable的API类实例代码及写法,或者点击链接到github查看源代码。
public ScrollSlidingTextTabStrip(Context context) {
super(context);
selectorDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, null);
float rad = AndroidUtilities.dpf2(3);
selectorDrawable.setCornerRadii(new float[]{rad, rad, rad, rad, 0, 0, 0, 0});
selectorDrawable.setColor(Theme.getColor(tabLineColorKey));
setFillViewport(true);
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
tabsContainer = new LinearLayout(context) {
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
ScrollSlidingTextTabStrip.this.invalidate();
}
};
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setPadding(AndroidUtilities.dp(7), 0, AndroidUtilities.dp(7), 0);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
addView(tabsContainer);
}
/**
* Returns a corner drawable which can be used for the theme preview header.
*
* @param width The width in dip for the drawable.
* @param height The height in dip for the drawable.
* @param cornerRadius The corner size in dip for the drawable.
* @param color The color for the drawable.
* @param topOnly {@code true} to round the top corners only.
*/
public static Drawable getCornerDrawableLegacy(int width, int height,
float cornerRadius, @ColorInt int color, boolean topOnly) {
float adjustedCornerRadius = cornerRadius;
if (!topOnly) {
return DynamicDrawableUtils.getCornerDrawable(
width, height, adjustedCornerRadius, color);
} else {
adjustedCornerRadius = Math.max(0, cornerRadius - 1f);
adjustedCornerRadius = DynamicUnitUtils.convertDpToPixels(adjustedCornerRadius);
GradientDrawable drawable = new GradientDrawable();
drawable.setCornerRadii(new float[] {
adjustedCornerRadius, adjustedCornerRadius,
adjustedCornerRadius, adjustedCornerRadius,
0, 0, 0, 0 });
return DynamicDrawableUtils.getCornerDrawable(width, height, drawable, color);
}
}
@NonNull
private Drawable createThemedBackground() {
float cornerRadius =
getResources().getDimension(R.dimen.mtrl_snackbar_background_corner_radius);
GradientDrawable background = new GradientDrawable();
background.setShape(GradientDrawable.RECTANGLE);
background.setCornerRadius(cornerRadius);
int backgroundColor =
MaterialColors.layer(
this, R.attr.colorSurface, R.attr.colorOnSurface, getBackgroundOverlayColorAlpha());
background.setColor(backgroundColor);
if (backgroundTint != null) {
Drawable wrappedDrawable = DrawableCompat.wrap(background);
DrawableCompat.setTintList(wrappedDrawable, backgroundTint);
return wrappedDrawable;
} else {
return DrawableCompat.wrap(background);
}
}
public ScrollSlidingTextTabStrip(Context context) {
super(context);
selectorDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, null);
float rad = AndroidUtilities.dpf2(3);
selectorDrawable.setCornerRadii(new float[]{rad, rad, rad, rad, 0, 0, 0, 0});
selectorDrawable.setColor(Theme.getColor(tabLineColorKey));
setFillViewport(true);
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
tabsContainer = new LinearLayout(context) {
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
ScrollSlidingTextTabStrip.this.invalidate();
}
};
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setPadding(AndroidUtilities.dp(7), 0, AndroidUtilities.dp(7), 0);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
addView(tabsContainer);
}
@Override
protected void drawCurrentPageShadow(Canvas canvas) {
canvas.save();
GradientDrawable shadow;
if (actiondownX > mScreenWidth >> 1) {
shadow = mBackShadowDrawableLR;
shadow.setBounds((int) (mScreenWidth + touch_down - 5), 0, (int) (mScreenWidth + touch_down + 5), mScreenHeight);
} else {
shadow = mBackShadowDrawableRL;
shadow.setBounds((int) (touch_down - 5), 0, (int) (touch_down + 5), mScreenHeight);
}
shadow.draw(canvas);
try {
canvas.restore();
} catch (Exception e) {
}
}
protected void iconChanged ()
{
if (! this.isInEditMode () && (this.icon != null))
{
ImageView imgIcon = (ImageView) this.findViewById (R.id.imgIcon);
imgIcon.setImageDrawable (this.icon.getDrawable ());
LinearLayout llBackground = (LinearLayout) this.findViewById (R.id.llBackground);
if (llBackground != null && (! this.special) && this.getResources ().getBoolean (HomeActivity.theme.launcher_applauncher_backgroundcolour_dynamic))
{
final SharedPreferences prefs = Preferences.getSharedPreferences(this.context, Preferences.PREFERENCES);
final int avgColour = this.icon.getAverageColour(prefs.getInt (Preference.LAUNCHERICON_OPACITY.getName(), 204));
final GradientDrawable gd = (GradientDrawable) llBackground.getBackground ();
gd.setColor (avgColour);
}
}
}
private void setCurThemeBtn() {
Button usedButton = mThemeBtns[mTheme];
for (int i = 0; i < mThemeBtns.length; i++) {
// 设置背景填充颜色
GradientDrawable drawable = (GradientDrawable) mThemeBtns[i].getBackground();
drawable.setColor(mPopupColors[i]);
//设置边框颜色
if (mThemeBtns[i].getId() == usedButton.getId()) {
int strokeColor = mStrokeColors[i];
drawable.setStroke(5, strokeColor);
} else {
drawable.setStroke(5, mPopupColors[i]); //未选择button的边框颜色和填充颜色一致
}
}
}
protected GradientDrawable.Orientation getDropShadowOrientation() {
// Gets the orientation for the static and sliding drawer. The overlay drawer provides its own implementation.
switch (mPosition) {
case TOP:
return GradientDrawable.Orientation.BOTTOM_TOP;
case RIGHT:
return GradientDrawable.Orientation.LEFT_RIGHT;
case BOTTOM:
return GradientDrawable.Orientation.TOP_BOTTOM;
default:
return GradientDrawable.Orientation.RIGHT_LEFT;
}
}
@SuppressWarnings("deprecation")
@Override
protected void drawProgress(LinearLayout layoutProgress, float max, float progress, float totalWidth,
int radius, int padding, int colorProgress, boolean isReverse) {
GradientDrawable backgroundDrawable = createGradientDrawable(colorProgress);
int newRadius = radius - (padding / 2);
if (isReverse && progress != max)
backgroundDrawable.setCornerRadii(new float[]{newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius});
else
backgroundDrawable.setCornerRadii(new float[]{0, 0, newRadius, newRadius, newRadius, newRadius, 0, 0});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layoutProgress.setBackground(backgroundDrawable);
} else {
layoutProgress.setBackgroundDrawable(backgroundDrawable);
}
float ratio = max / progress;
int progressWidth = (int) ((totalWidth - ((padding * 2) + ivProgressIcon.getWidth())) / ratio);
ViewGroup.LayoutParams progressParams = layoutProgress.getLayoutParams();
progressParams.width = progressWidth;
layoutProgress.setLayoutParams(progressParams);
}
public void setDay(int daysOfWeek, boolean selected) {
this.daysOfWeek = daysOfWeek;
dayOfWeekView.setText(getStringForDayOfWeek(daysOfWeek));
dayOfWeekView.setSelected(selected);
GradientDrawable gradientDrawable = (GradientDrawable) getResources().getDrawable(R.drawable.btn_circular_normal);
gradientDrawable.setColor(selected ? selectedRippleColor : unSelectedRippleColor);
rippleBackgroundView.setBackgroundDrawable(gradientDrawable);
}
private Drawable createBackgroundColorDrawable() {
GradientDrawable mask = new GradientDrawable();
mask.setShape(GradientDrawable.OVAL);
if (mOutlineWidth != 0) {
int color = mOutlineColor;
if (color == AUTO){
color = isColorDark(mColor) ? Color.WHITE : Color.BLACK;
}
mask.setStroke(mOutlineWidth, color);
}
mask.setColor(mColor);
return mask;
}
private GradientDrawable getShape() {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadius(getTypedValueInDP(context, DEFAULT_CORNER_RADIUS));
gradientDrawable.setColor(DEFAULT_BACKGROUND);
gradientDrawable.setAlpha(DEFAULT_ALPHA);
return gradientDrawable;
}
/**
* 设置Button背景颜色
*
* @return
*/
public static Drawable setButtonBackgroundColor() {
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setCornerRadii(new float[] { 50, 50, 50, 50, 50, 50, 50, 50 });
String ButtonColor_FromMap = infoMap.get(ButtonColor_Key).toString();
if (!TextUtils.isEmpty(ButtonColor_FromMap)) {
drawable.setColor(Color.parseColor("#" + ButtonColor_FromMap));
} else {
drawable.setColor(context.getResources().getColor(R.color.yellow));
}
return drawable;
}
/**
* Some drawable implementations have problems with mutation. This method returns false if
* there is a known issue in the given drawable's implementation.
*/
public static boolean canSafelyMutateDrawable(@NonNull Drawable drawable) {
if (Build.VERSION.SDK_INT < 15 && drawable instanceof InsetDrawable) {
return false;
} else if (Build.VERSION.SDK_INT < 15 && drawable instanceof GradientDrawable) {
// GradientDrawable has a bug pre-ICS which results in mutate() resulting
// in loss of color
return false;
} else if (Build.VERSION.SDK_INT < 17 && drawable instanceof LayerDrawable) {
return false;
}
if (drawable instanceof DrawableContainer) {
// If we have a DrawableContainer, let's traverse it's child array
final Drawable.ConstantState state = drawable.getConstantState();
if (state instanceof DrawableContainer.DrawableContainerState) {
final DrawableContainer.DrawableContainerState containerState =
(DrawableContainer.DrawableContainerState) state;
for (final Drawable child : containerState.getChildren()) {
if (!canSafelyMutateDrawable(child)) {
return false;
}
}
}
} else if (SkinCompatVersionUtils.isV4DrawableWrapper(drawable)) {
return canSafelyMutateDrawable(SkinCompatVersionUtils.getV4DrawableWrapperWrappedDrawable(drawable));
} else if (SkinCompatVersionUtils.isV4WrappedDrawable(drawable)) {
return canSafelyMutateDrawable(SkinCompatVersionUtils.getV4WrappedDrawableWrappedDrawable(drawable));
} else if (drawable instanceof DrawableWrapper) {
return canSafelyMutateDrawable(((DrawableWrapper) drawable).getWrappedDrawable());
} else if (drawable instanceof ScaleDrawable) {
return canSafelyMutateDrawable(((ScaleDrawable) drawable).getDrawable());
}
return true;
}
/**
* Set drawable as divider between buttons with a specified width, corner radius and padding
*
* If the drawable is null, then the divider will be removed and hidden
*
* @param drawable divider drawable that will be displayed between buttons
* @param width width of the divider drawable, in pixels
* @param radius corner radius of the divider drawable to round the corners, in pixels
* @param padding space above and below the divider drawable within the button group, in pixels
*/
public void setDivider(@Nullable Drawable drawable, int width, int radius, int padding)
{
// Drawable of null indicates that we want to hide dividers
if (drawable == null)
{
dividerLayout.setDividerDrawable(null);
dividerLayout.setShowDividers(SHOW_DIVIDER_NONE);
return;
}
// Set the corner radius and size if the drawable is a GradientDrawable
// Otherwise just set the divider drawable like normal because we cant set the parameters
if (drawable instanceof GradientDrawable)
{
GradientDrawable gradient = (GradientDrawable)drawable;
gradient.setSize(width, 0);
gradient.setCornerRadius(radius);
dividerLayout.setDividerDrawable(gradient);
}
else
{
dividerLayout.setDividerDrawable(drawable);
}
dividerLayout.setDividerPadding(padding);
dividerLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);
// Loop through and update the divider width for each of the dummy divider views
for (int i = 0; i < dividerLayout.getChildCount(); ++i)
{
final ButtonActor view = (ButtonActor)dividerLayout.getChildAt(i);
view.setDividerWidth(width);
}
dividerLayout.requestLayout();
}
private Drawable getBackground() {
if (mBackground instanceof ColorDrawable) {
if (mBackgroundRadius > 0) {
GradientDrawable back = new GradientDrawable();
back.setCornerRadius(mBackgroundRadius);
back.setColor(((ColorDrawable) mBackground).getColor());
mBackground = back;
}
}
return mBackground;
}
private void initSquare(Context context) {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(mSquareColor);
gradientDrawable.setSize(mSquareSize, mSquareSize);
gradientDrawable.setCornerRadius(mSquareCorner);
for (int i = 0; i < mXCount * mYCount; i++) {
ImageView image = new ImageView(context);
image.setImageDrawable(gradientDrawable);
addView(image);
}
}
private View getItemView(int position, View convertView, @NonNull ViewGroup parent, boolean colorize)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.layout_listitem_timezone, parent, false);
TimeZoneItem timezone = getItem(position);
if (timezone == null)
{
Log.w("getItemView", "timezone at position " + position + " is null.");
return view;
}
TextView primaryText = (TextView)view.findViewById(android.R.id.text1);
primaryText.setText(String.format(line1, timezone.getID()));
TextView secondaryText = (TextView)view.findViewById(android.R.id.text2);
if (secondaryText != null)
{
secondaryText.setText(String.format(line2, timezone.getOffsetString(), timezone.getDisplayString()));
}
ImageView icon = (ImageView) view.findViewById(android.R.id.icon);
if (icon != null)
{
if (colorize)
{
GradientDrawable d = (GradientDrawable) icon.getBackground().mutate();
d.setColor(getColorForTimeZoneOffset(timezone.getOffsetHr()));
d.invalidateSelf();
icon.setVisibility(View.VISIBLE);
} else {
icon.setVisibility(View.GONE);
}
}
return view;
}
private void setBackground() {
final GradientDrawable background = this.gradientBackground.generate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.setBackground(background);
} else {
this.setBackgroundDrawable(background);
}
}
private void initViews() {
container = findViewById(R.id.splash_container);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TL_BR,
new int[]{
getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark)
});
container.setBackground(gd);
container.setClickable(false);
ts = new TextView[]{
(TextView) findViewById(R.id.splash_m),
(TextView) findViewById(R.id.splash_u),
(TextView) findViewById(R.id.splash_s),
(TextView) findViewById(R.id.splash_i),
(TextView) findViewById(R.id.splash_c),
(TextView) findViewById(R.id.splash_o),
(TextView) findViewById(R.id.splash_c1),
(TextView) findViewById(R.id.splash_o1)
};
ts[0].post(new Runnable() {
@Override
public void run() {
for (TextView t : ts) {
t.setVisibility(View.VISIBLE);
startTextInAnim(t);
}
}
});
}
private int getGradientType(@Nullable String type) {
if (null == type) {
return GRADIENT_TYPE_NONE;
}
switch (type) {
case LINEAR_GRADIENT:
return GradientDrawable.LINEAR_GRADIENT;
case RADIAL_GRADIENT:
return GradientDrawable.RADIAL_GRADIENT;
case SWEEP_GRADIENT:
return GradientDrawable.SWEEP_GRADIENT;
default:
return GRADIENT_TYPE_NONE;
}
}
@Override
public void setEnabled(final boolean enabled) {
mIsEnabled = enabled;
triggerMethodOnceViewIsDisplayed(this, new Callable<Void>() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public Void call() throws Exception {
if (!lollipopAndAbove()) {
gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setSize(mOriginalThumbHeight / 3, mOriginalThumbHeight / 3);
gradientDrawable.setColor(mIsEnabled ? mThumbColor : Color.LTGRAY);
gradientDrawable.setDither(true);
gradientDrawable.setAlpha(mThumbAlpha);
setThumb(gradientDrawable);
//load up the drawable and apply color
LayerDrawable ld = (LayerDrawable) getProgressDrawable();
ScaleDrawable shape = (ScaleDrawable) (ld.findDrawableByLayerId(android.R.id.progress));
shape.setColorFilter(mIsEnabled ? mProgressColor : Color.LTGRAY, PorterDuff.Mode.SRC_IN);
//set the background to transparent
NinePatchDrawable ninePatchDrawable = (NinePatchDrawable) (ld.findDrawableByLayerId(android.R.id.background));
ninePatchDrawable.setColorFilter(Color.TRANSPARENT, PorterDuff.Mode.SRC_IN);
//background
//load up the drawable and apply color
SeekBarBackgroundDrawable seekBarBackgroundDrawable = new SeekBarBackgroundDrawable(getContext(),
mIsEnabled ? mProgressBackgroundColor : Color.LTGRAY, mActualBackgroundColor, getPaddingLeft(), getPaddingRight());
if (belowJellybean())
setBackgroundDrawable(seekBarBackgroundDrawable);
else
setBackground(seekBarBackgroundDrawable);
}
SeekBarCompat.super.setEnabled(enabled);
return null;
}
});
}
private void setSeekBarBg(){
try {
int progressColor = CustomAttrValueUtil.getAttrColorValue(R.attr.colorPrimary,R.color.colorAccent,this);
LayerDrawable layerDrawable = (LayerDrawable) seekBar.getProgressDrawable();
ScaleDrawable scaleDrawable = (ScaleDrawable)layerDrawable.findDrawableByLayerId(android.R.id.progress);
GradientDrawable drawable = (GradientDrawable) scaleDrawable.getDrawable();
drawable.setColor(progressColor);
}catch (Exception e){
e.printStackTrace();
}
}
private GradientDrawable createGradientDrawableWithCorner(LinearLayout layout, int color) {
GradientDrawable backgroundDrawable = createGradientDrawable(color);
int newRadius = radius;
backgroundDrawable.setCornerRadii(new float[]{newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius});
// backgroundDrawable.setCornerRadii(new float[]{0, 0, newRadius, newRadius, newRadius, newRadius, 0, 0});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackground(backgroundDrawable);
} else {
layout.setBackgroundDrawable(backgroundDrawable);
}
return backgroundDrawable;
}
public CoverPageAnim(int w, int h, View view, OnPageChangeListener listener) {
super(w, h, view, listener);
mSrcRect = new Rect(0, 0, mViewWidth, mViewHeight);
mDestRect = new Rect(0, 0, mViewWidth, mViewHeight);
int[] mBackShadowColors = new int[]{0x66000000, 0x00000000};
mBackShadowDrawableLR = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, mBackShadowColors);
mBackShadowDrawableLR.setGradientType(GradientDrawable.LINEAR_GRADIENT);
}
@Override
public void apply(ProteusView view, Context context, ProteusLayoutInflater.ImageLoader loader, Callback callback) {
GradientDrawable drawable = null != gradient ? gradient.init(view) : new GradientDrawable();
if (-1 != shape) {
drawable.setShape(shape);
}
if (null != elements) {
for (DrawableElement element : elements) {
element.apply(view, drawable);
}
}
callback.apply(drawable);
}
public void notificationColorClick(int color, boolean updateUi) {
if (fragmentThemColorCustomBinding != null) {
GradientDrawable bgShape = (GradientDrawable) fragmentThemColorCustomBinding.asnImgNotificationColor.getBackground();
bgShape.setColor(Color.parseColor(G.notificationColor));
}
}
public CT(Builder builder) {
LayoutInflater inflater = (LayoutInflater) builder.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout, null);
TextView tv = layout.findViewById(R.id.cltv);
tv.setText(builder.text);
tv.setTextColor(builder.textCol);
ImageView iv = layout.findViewById(R.id.cliv);
iv.setImageResource(builder.imageRes);
GradientDrawable shape = new GradientDrawable();
shape.setShape(builder.shape);
shape.setCornerRadii(new float[]{
builder.radiusTopLeft,
builder.radiusTopLeft,
builder.radiusTopRight,
builder.radiusTopRight,
builder.radiusBottomRight,
builder.radiusBottomRight,
builder.radiusBottomLeft,
builder.radiusBottomLeft
});
shape.setColor(builder.backCol);
shape.setStroke(builder.borderWidth, builder.borderCol);
layout.setBackgroundDrawable(shape);
Toast toast = new Toast(builder.context);
toast.setView(layout);
toast.setDuration(builder.toastDuration);
toast.setGravity(builder.toastGravity,0,100);
toast.show();
}
public static void shapeUse() {
Button vid_btn1 = null;
// 默认就设置背景色
ShapeUtils.Builder builder = new ShapeUtils.Builder();
builder.setRadiusLeft(10f).setColor(R.color.black);
ViewUtils.setBackground(vid_btn1, builder.build().getDrawable());
// 设置点击效果
GradientDrawable drawable1 = ShapeUtils.newBuilder(10f, R.color.black).setStroke(5, R.color.green).build().getDrawable();
GradientDrawable drawable2 = ShapeUtils.newBuilder(10f, R.color.sky_blue).setStroke(5, R.color.gray).build().getDrawable();
ViewUtils.setBackground(vid_btn1, StateListUtils.newSelector(drawable2, drawable1)); // 设置点击 View 背景变色, 不用写 shape xml 文件
vid_btn1.setTextColor(StateListUtils.createColorStateList(R.color.red, R.color.white)); // 设置点击字体变色
// 设置渐变
View vid_view1 = null;
// int[] colors = new int[]{ Color.RED, Color.BLUE, Color.GREEN };
int[] colors = new int[3];
colors[0] = ContextCompat.getColor(DevUtils.getContext(), R.color.black);
colors[1] = ContextCompat.getColor(DevUtils.getContext(), R.color.sky_blue);
colors[2] = ContextCompat.getColor(DevUtils.getContext(), R.color.orange);
// ShapeUtils.newBuilderToGradient(GradientDrawable.Orientation.BR_TL, colors).build().setDrawable(vid_view1);
GradientDrawable drawable = ShapeUtils.newBuilderToGradient(GradientDrawable.Orientation.BR_TL, colors).build().getDrawable();
// drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); // 线性渐变, 这是默认设置
// drawable.setGradientType(GradientDrawable.RADIAL_GRADIENT); // 放射性渐变, 以开始色为中心
drawable.setGradientType(GradientDrawable.SWEEP_GRADIENT); // 扫描线式的渐变
ViewUtils.setBackground(vid_view1, drawable);
}
public static Drawable cornerDrawable(final int bgColor, float[] cornerradius, int borderwidth, int bordercolor) {
final GradientDrawable bg = new GradientDrawable();
bg.setCornerRadii(cornerradius);
bg.setStroke(borderwidth, bordercolor);
bg.setColor(bgColor);
return bg;
}