RoundedCornerHelper 控制
public class RoundedCornerHelper { private Paint paint; private RectF rectF; private float cornerRadiusPercentage = 0.5f; // 默认 50% private float calculatedRadius; private int backgroundColor = 0x99636363; // 默认颜色 public RoundedCornerHelper(Context context, AttributeSet attrs) { paint = new Paint(Paint.ANTI_ALIAS_FLAG); rectF = new RectF(); if (attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PercentageRoundedView); cornerRadiusPercentage = a.getFloat(R.styleable.PercentageRoundedView_cornerRadiusPercentage, cornerRadiusPercentage); backgroundColor = a.getColor(R.styleable.PercentageRoundedView_backgroundColor, backgroundColor); a.recycle(); } paint.setColor(backgroundColor); } public void onSizeChanged(int width, int height) { calculatedRadius = Math.min(width, height) * cornerRadiusPercentage; } public void onDraw(Canvas canvas, View view) { rectF.set(0, 0, view.getWidth(), view.getHeight()); canvas.drawRoundRect(rectF, calculatedRadius, calculatedRadius, paint); } public void setCornerRadiusPercentage(float percentage, View view) { cornerRadiusPercentage = Math.max(0f, Math.min(percentage, 1f)); calculatedRadius = Math.min(view.getWidth(), view.getHeight()) * cornerRadiusPercentage; view.invalidate(); } public void setBackgroundColorCustom(int color, View view) { backgroundColor = color; paint.setColor(backgroundColor); view.invalidate(); } public int getBackgroundColorCustom() { return backgroundColor; } public float getCornerRadiusPercentage() { return cornerRadiusPercentage; } }
PercentageRoundedTextView 实现
public class PercentageRoundedTextView extends android.support.v7.widget.AppCompatTextView { private RoundedCornerHelper roundedCornerHelper; public PercentageRoundedTextView(Context context) { super(context); init(null); } public PercentageRoundedTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public PercentageRoundedTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { roundedCornerHelper = new RoundedCornerHelper(getContext(), attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { roundedCornerHelper.onSizeChanged(w, h); super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { roundedCornerHelper.onDraw(canvas, this); super.onDraw(canvas); } // 提供设置方法 public void setCornerRadiusPercentage(float percentage) { roundedCornerHelper.setCornerRadiusPercentage(percentage, this); } public void setBackgroundColorCustom(int color) { roundedCornerHelper.setBackgroundColorCustom(color, this); } public int getBackgroundColorCustom() { return roundedCornerHelper.getBackgroundColorCustom(); } public float getCornerRadiusPercentage() { return roundedCornerHelper.getCornerRadiusPercentage(); } }