3.5.3 重写View来实现全新的控件
先分析自定义View的组成,然后一步一步进行绘制
代码如下:
int mCircleXY, mRadius;
Paint mCirclepaint, mArcPaint, mTextPaint;
RectF mArcrectf;
private String mText = "Hello World";
private int length = 800;
private int sweepAngle = 270;
private int circleTextSize = 40;
private float msweepValue;
public Bilitu(Context context) {
super(context);
}
public Bilitu(Context context, AttributeSet attrs) {
super(context, attrs);
//圆心坐标
mCircleXY = length / 2;
mRadius = length / 4;
//弧线绘制
mArcrectf = new RectF((float) (length * 0.1), (float) (length * 0.1), (float) (length * 0.9), (float) (length * 0.9));
//画笔实例
mTextPaint = new Paint();
mTextPaint.setColor(Color.RED);
mTextPaint.setTextSize(circleTextSize);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mArcPaint = new Paint();
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setColor(Color.YELLOW);
mArcPaint.setStrokeWidth(45);
mCirclepaint = new Paint();
mCirclepaint.setColor(Color.BLUE);
}
//重写onDraw()方法,
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画圆
canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclepaint);
//画弧
canvas.drawArc(mArcrectf, sweepAngle, msweepValue, false, mArcPaint);
//文字格式
canvas.drawText(mText, 0, mText.length(), mCircleXY, mCircleXY + (circleTextSize / 4), mTextPaint);
}
//开发者可以选择不同的状态值,默认是25
public void setSweepValue(float sweepValue) {
if (sweepValue != 0) {
msweepValue = sweepValue;
} else {
msweepValue = 25;
}
}