public class SportView extends View {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint paintText = new Paint();
private static final float RADIUS = Util.dp2px(150);
private static final float STROKE_WIDTH = Util.dp2px(20);
private static final int CIRCLE_COLOR = Color.GRAY;
private static final int ARC_COLOR = Color.RED;
private static final int START_ANGLE = 270;
private static final int SWEEP_ANGLE = 280;
public SportView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
Rect rect = new Rect();
private Paint.FontMetrics fontMetrics = new Paint.FontMetrics();
{
paint.setTextSize(Util.dp2px(90));
// paint.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Quicksand-Regular.ttf"));
paint.setTextAlign(Paint.Align.CENTER);
paint.getFontMetrics(fontMetrics);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制圆环
paint.setColor(CIRCLE_COLOR);
paint.setStrokeWidth(STROKE_WIDTH);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(getWidth()/2, getHeight()/2, RADIUS, paint);
// 绘制进度条
paint.setColor(ARC_COLOR);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
canvas.drawArc(getWidth()/2-RADIUS, getHeight()/2-RADIUS, getWidth()/2+RADIUS, getHeight()/2+RADIUS,
START_ANGLE, SWEEP_ANGLE, false, paint);
// 绘制文字
paint.setStyle(Paint.Style.FILL);
String value = "ggghhh";
// 方式一
// paint.getTextBounds(value, 0, value.length(), rect);
// float offset = (rect.bottom-rect.top)/2.0f;
// 方式二
float offset = (fontMetrics.ascent+fontMetrics.descent)/2.0f;
canvas.drawText(value, getWidth()/2, getHeight()/2 + offset, paint);
// StaticLayout
}
}
评论