2、画彩色圆环
使用SweepGradient来实现圆环渐变的效果,这里有个判断当设置的颜色数组只有一个颜色的时候,直接'setColor',有多个颜色才使用SweepGradient实现渐变色。这样就能既支持渐变色又支持单色。
这里还有一点要注意,SweepGradient默认是从3点钟位置开始渐变的,为了能让它从12点钟位置开始渐变所以将画布旋转了-90°。
//画彩色圆环
initPaint();
canvas.rotate(-90, width / 2, height / 2);
paint.setStrokeWidth(doughnutWidth);
paint.setStyle(Paint.Style.STROKE);
if (doughnutColors.length > 1) {
paint.setShader(new SweepGradient(width / 2, height / 2, doughnutColors, null));
} else {
paint.setColor(doughnutColors[0]);
}
canvas.drawArc(rectF, 0, currentValue, false, paint);
3、画中间数值的白色背景(只是为了让数值显示更明显一些)
//画中间数值的背景 int fontSize = 50; initPaint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.WHITE); canvas.drawCircle(width / 2, height / 2, fontSize * 2, paint);}
4、画中间数值
//画中间数值 canvas.rotate(90, width / 2, height / 2); initPaint(); paint.setColor(ColorUtils.getCurrentColor(currentValue / 360f, doughnutColors)); paint.setTextSize(fontSize); paint.setTextAlign(Paint.Align.CENTER); float baseLine = height / 2 - (paint.getFontMetrics().descent + paint.getFontMetrics().ascent) / 2; canvas.drawText((int) (currentValue / 360f * 100) + "%", width / 2, baseLine, paint);
这里有两点比较坑:
1、数值的颜色
要实现的效果是让数值的颜色是跟彩色圆环终点的颜色是一样的。寻寻觅觅很久也没有找到获取SweepGradient渲染到某一个角度时颜色的方法=_=
最终花了差不多半天时间写了个颜色渐变算法,代码如下:
/**
* 颜色渐变算法
* 获取某个百分比下的渐变颜色值
*
* @param percent
* @param colors
* @return
*/
public static int getCurrentColor(float percent, int[] colors) {
float[][] f = new float[colors.length][3];
for (int i = 0; i < colors.length; i++) {
f[i][0] = (colors[i] & 0xff0000) >> 16;
f[i][1] = (colors[i] & 0x00ff00) >> 8;
f[i][2] = (colors[i] & 0x0000ff);
}
float[] result = new float[3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < f.length; j++) {
if (f.length == 1 || percent == j / (f.length - 1f)) {
result = f[j];
} else {
if (percent > j / (f.length - 1f) && percent < (j + 1f) / (f.length - 1)) {
result[i] = f[j][i] - (f[j][i] - f[j + 1][i]) * (percent - j / (f.length - 1f)) * (f.length - 1f);
}
}
}
}
return Color.rgb((int) result[0], (int) result[1], (int) result[2]);
}










