我正在研究android中的饼图。 由于我不能使用像aChartEngine这样的库,我使用以下代码绘制饼图: -
public class Chart extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float[] value_degree;
private String[] Title_value;
RectF rectf = new RectF(50, 5, 200, 150);
Rect rect = new Rect(50, 5, 200, 150);
float temp = 0;
public Chart(Context context, float[] values, String[] heading)
{
super(context);
value_degree = new float[values.length];
Title_value = new String[heading.length];
for (int i = 0; i < values.length; i++)
{
value_degree[i] = values[i];
Title_value[i] = heading[i];
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Random r;
int centerX = (rect.left + rect.right) / 2;
int centerY = (rect.top + rect.bottom) / 2;
int radius = (rect.right - rect.left) / 2;
radius *= 0.5; // 1 will put the text in the border, 0 will put the text in the center. Play with this to set the distance of your text.
for (int i = 0; i < value_degree.length; i++)
{
if (i == 0)
{
r = new Random();
int color = Color.argb(100, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
paint.setColor(Color.BLACK); // set this to the text color.
paint.setTextSize(12);
/*paint.setTextAlign(Align.CENTER);
*/float medianAngle = (temp + (value_degree[i] / 2f)) * (float)Math.PI / 180f; // this angle will place the text in the center of the arc.
canvas.drawText(Title_value[i], (float)(centerX + (radius * Math.cos(medianAngle))), (float)(centerY + (radius * Math.sin(medianAngle))), paint);
}
else
{
temp += value_degree[i - 1];
r = new Random();
int color = Color.argb(255, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
paint.setColor(Color.BLACK); // set this to the text color.
paint.setTextSize(12);
/*paint.setTextAlign(Align.CENTER);
*/float medianAngle = (temp + (value_degree[i] / 2f)) * (float)Math.PI / 180f; // this angle will place the text in the center of the arc.
canvas.drawText(Title_value[i], (float)(centerX + (radius * Math.cos(medianAngle))), (float)(centerY + (radius * Math.sin(medianAngle))), paint);
}
}
}
}
从数据库传递浮点值和标题。现在我需要自己为每个切片分配颜色而不是随机。我怎么能这样做? 或者请告诉我如何使用上面的代码为每个切片分配颜色值。
此外,我需要计算每个切片的百分比值并显示标题。 怎么做到这一点?
如果有任何建议,请帮助我。
提前致谢。