@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 画最外层的大圆环
*/
int centre = getWidth() / 2; // 获取圆心的x坐标
int radius = (int) (centre - roundWidth / 4); // 圆环的半径
paint.setColor(roundColor); // 设置圆环的颜色
paint.setStyle(Paint.Style.STROKE); // 设置空心
paint.setStrokeWidth(roundWidth / 5); // 设置圆环的宽度
paint.setAntiAlias(true); // 消除锯齿
canvas.drawCircle(centre, centre, radius, paint); // 画出圆环
Log.e("log", centre + "");
/**
* 画进度百分比文字
*/
paint.setStrokeWidth(0);
paint.setColor(textColor);
if (upTextSize != null) {
paint.setTextSize(
SizeUtils.sp2px(getIntstance().getApplicationContext(), upTextSize));
} else {
paint.setTextSize(50);
}
paint.setStyle(Paint.Style.FILL); // 设置字是空心还是实心
paint.setTypeface(Typeface.DEFAULT_BOLD); // 设置字体
int percent;
if (withPercent) {
percent = (int) (((float) progress / (float) max) * 100); // 中间的进度百分比,先转换成float在进行除法运算,不然都为0
} else {
percent = progress;
}
float textWidth;
if (withPercent) {
textWidth = paint.measureText(percent + "%"); // 测量字体宽度,我们需要根据字体的宽度设置在圆环中间
} else {
textWidth = paint.measureText(changeCountToK(progress) + ""); // 测量字体宽度,我们需要根据字体的宽度设置在圆环中间
}
if (textIsDisplayable && style == STROKE) {
if (withPercent) {
canvas.drawText(percent + "%", centre - textWidth / 2, centre - 10, paint); // 画出进度百分比
} else {
canvas.drawText(percent + "", centre - textWidth / 2 - 8, centre + 20, paint); // 画出进度百分比
}
}
/**
* 画进度比下的文字
*/
paint.setStrokeWidth(0);
try {
paint.setColor(ContextCompat.getColor(getIntstance().getApplicationContext(), R.color.text_gray));
} catch (NullPointerException e) {
e.printStackTrace();
}
if (downTextSize != null) {
paint.setTextSize(SizeUtils.sp2px(getIntstance().getApplicationContext(), downTextSize));
} else {
paint.setTextSize(35);
}
paint.setTypeface(Typeface.DEFAULT); // 设置字体
float textWidth2 = paint.measureText(textPercent); // 百分比下面的文字的高度
float txH2 = paint.getFontMetrics().descent - paint.getFontMetrics().ascent;// 第二行汉子的高度
if (textIsDisplayable && style == STROKE) {
if (withPercent) {
canvas.drawText(textPercent, centre - textWidth2 / 2 + 2, centre + txH2, paint); //
} else {
canvas.drawText(textPercent, centre - textWidth / 2 + textWidth + 2, centre + 20, paint); //
}
}
/**
* 画圆弧 ,画圆环的进度
*/
// 设置进度是实心还是空心
paint.setStrokeWidth(roundWidth / 5); // 设置圆环的宽度
paint.setColor(roundProgressColor); // 设置进度的颜色
RectF oval = new RectF(centre - radius, centre - radius, centre
+ radius, centre + radius); // 用于定义的圆弧的形状和大小的界限
switch (style) {
case STROKE: {
paint.setStyle(Paint.Style.STROKE);
canvas.drawArc(oval, 0, 360 * progress / max, false, paint); // 根据进度画圆弧
break;
}
case FILL: {
paint.setStyle(Paint.Style.FILL_AND_STROKE);
if (progress != 0)
canvas.drawArc(oval, 0, 360 * progress / max, true, paint); // 根据进度画圆弧
break;
}
}
}
|