自定义扇形图
//扇形图实体类
public class FanBean {
private float num;//数值
private float percent;//所占百分比
private int color;//颜色
public FanBean(float num, float percent, int color) {
this.num = num;
this.percent = percent;
this.color = color;
}
public float getNum() {
return num;
}
public float getPercent() {
return percent;
}
public int getColor() {
return color;
}
}
/**
* 描述:
* 绘制扇形图
*
* @outhor zhengqian
* @create 2018-10-09 16:37
*/
public class PieView extends View {
private Paint mPaint;//画笔
private ArrayList<FanBean> fanBeanList;
private float startAngle = 0;//初始角度
private int mWidth, mHeight;
public PieView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
//初始化画笔
private void init() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
protected void onDraw(Canvas canvas) {
/*
*
练习扇形图
1、数值
2、颜色
3、百分比
*
*/
canvas.translate(mWidth / 2, mHeight / 2);
float r = (float) (Math.min(mWidth, mHeight) / 2 * 0.4);
Log.d("BBFZ", r + "");
RectF rect = new RectF(-r, -r, r, r);
for (int i = 0; i < fanBeanList.size(); i++) {
FanBean fanBean = fanBeanList.get(i);
mPaint.setColor(fanBean.getColor());
canvas.drawArc(rect, startAngle,
fanBean.getPercent(), true, mPaint);//圆弧
startAngle += fanBean.getPercent();
}
}
public void setFanBeanList(ArrayList<FanBean> fanBeanList) {
if (fanBeanList == null || fanBeanList.size() == 0) return;
this.fanBeanList = fanBeanList;
invalidate();//重绘
}
}
//使用方法
XML定义
在类中设置数据即可 pieView.setFanBeanList(fanBeanList);