简书链接:圆形进度条实现方案
文章字数:64,阅读全文大约需要1分钟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas);
//画背景圆环 int center = getWidth() / 2;
float radius = center - roundWidth / 2; paint.setColor(roundColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(roundWidth); // 圆环的宽度 paint.setAntiAlias(true); canvas.drawCircle(center,center,radius,paint);
// 画进度百分比 paint.setColor(textColor); paint.setStrokeWidth(0); paint.setTextSize(textSize); paint.setTypeface(Typeface.DEFAULT_BOLD);
int percent = (int)(progress / (float)max * 100); String strPercent = percent + "%"; Paint.FontMetricsInt fm = paint.getFontMetricsInt(); if(percent != 0){ canvas.drawText(strPercent, getWidth() / 2 - paint.measureText(strPercent) / 2 , getWidth() / 2 +(fm.bottom - fm.top)/2 - fm.bottom, paint); }
// 画圆弧 RectF oval = new RectF(center - radius, center - radius, center + radius, center + radius); paint.setColor(roundProgressColor); paint.setStrokeWidth(roundWidth); paint.setStyle(Paint.Style.STROKE); paint.setStrokeCap(Paint.Cap.ROUND); canvas.drawArc(oval, 0 , 360 * progress / max, false, paint);
}
public void setProgress(int progress){ if(progress < 0 ){ throw new IllegalArgumentException("进度Progress不能小于0"); } if(progress > max){ progress = max; } if(progress <= max){ this.progress = progress; postInvalidate(); } }
|