AI智能
改变未来

Android 自定义控件之饼状图

核心代码

@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//获取设置总数if (total == 0)for (int i = 0; i < pieCharts.size(); i++) {total += pieCharts.get(i).getValue();}//获取圆心坐标centerX = getPivotX();centerY = getPivotY();//获取圆的半径if (radius == 0)radius = getWidth() > getHeight() ? getHeight() / 2 : getWidth() / 2;//设置矩形区域normalRect();//绘制每个扇形for (int i = 0; i < pieCharts.size(); i++) {//当前扇形的角度sweep = 360 * (pieCharts.get(i).getValue() / total);//当前扇形的颜色sweepColor = Color.parseColor(pieCharts.get(i).getSweepColor());paint.setColor(sweepColor);//绘制扇形canvas.drawArc(rectF, startC, sweep, true, paint);drawLineBesideCir(canvas,startC);//下一个扇形的开始角度startC += sweep;}}/*** 设置矩形区域*/private void normalRect() {rectF.left = centerX - radius;rectF.top = centerY - radius;rectF.right = centerX + radius;rectF.bottom = centerY + radius;}private void drawLineBesideCir(Canvas canvas, float angel ) {int sth = 1;if (angel % 360 > 180 && angel % 360 < 360) {sth = -1;}float lineToX = (float) (getHeight() / 2 + Math.cos(Math.toRadians(-angel)) * radius);float lineToY = (float) (getHeight() / 2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * radius);canvas.drawLine(centerX, centerY, lineToX, lineToY, whiteLinePaint);}

效果图

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Android 自定义控件之饼状图