多渐变色自定义view
public class MulticolorGradeView extends View {
private float round;
private RectF mBackGroundRect;
private LinearGradient backGradient;
//默认画笔
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint mPaintText = new Paint();
int[] colorlist;
public MulticolorGradeView(Context context, AttributeSet attrs) {
super(context, attrs);
//按钮多渐变色添加
int color1 = Color.parseColor("#8600FF");
int color2 = Color.parseColor("#FF009A");
int color3 = Color.parseColor("#FF0099");
int color4 = Color.parseColor("#FF7846");
int color5 = Color.parseColor("#FF992E");
int color6 = Color.parseColor("#FFDB00");
//也可通过attr进行xml文件内的自定义设置
if (attrs != null) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyGradient);
color1 = typedArray.getColor(R.styleable.MyGradient_GradientcolorStart, color1);
color2 = typedArray.getColor(R.styleable.MyGradient_GradientcolorafterStart, color2);
color3 = typedArray.getColor(R.styleable.MyGradient_GradientcolorbeforeEnd, color3);
color4 = typedArray.getColor(R.styleable.MyGradient_GradientcolorEnd, color4);
round = typedArray.getDimension(R.styleable.MyGradient_Gradientround, dip2px(context, 10));
}
//设置抗锯齿
mPaint.setAntiAlias(true);
//设置防抖动
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.FILL);
mPaintText.setAntiAlias(true);
mPaintText.setDither(true);
colorlist = new int[]{color1, color2, color3, color4, color5, color6};
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBackGroundRect = new RectF(0, 0, w, h);
backGradient = new LinearGradient(0, 0, w, 0, colorlist, null, Shader.TileMode.CLAMP);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setShader(backGradient);
//绘制背景 圆角矩形
if (mBackGroundRect != null) {
canvas.drawRoundRect(mBackGroundRect, round, round, mPaint);
}
}
public static int dip2px(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
style
<!--自定义控件属性-->
<declare-styleable name="MyGradient">
<attr name="GradientcolorStart" format="reference" />
<attr name="GradientcolorEnd" format="reference" />
<attr name="GradientcolorafterStart" format="reference" />
<attr name="GradientcolorbeforeEnd" format="reference" />
<attr name="Gradientround" format="dimension" />
</declare-styleable>
网友评论