4.自定义view-进度条控件
1.效果
2.实现原理
画圆,画圆弧,画文字
外部控制进度,通过invalidate()方法更新
核心代码:
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
//1.画下面的圆
int center = getWidth() / 2;
int radius = center - mLineWidth / 2;
canvas.drawCircle(center, center, radius, mBelowPaint);
//2.画上面的圆弧
RectF rectF = new RectF(mLineWidth / 2, mLineWidth / 2, getWidth() - mLineWidth / 2, getHeight() - mLineWidth / 2);
canvas.drawArc(rectF, 0, mProcess * 360, false, mAbovePaint);
//3.画中间的文字
String text = (int) (mProcess * 100) + "%";
Rect rect = new Rect();
mTextPaint.getTextBounds(text, 0, text.length(), rect);
int x = getWidth() / 2 - rect.width() / 2;
Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
int dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
int baseLine = getHeight() / 2 + dy;
canvas.drawText(text, x, baseLine, mTextPaint);
}