android实现简单饼状图绘制

时间:2024-03-14 20:58:23
package com.example.lijingwen.defineview.cutomview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.support.annotation.UiThread
import android.util.AttributeSet
import android.view.View
import com.example.lijingwen.defineview.databean.PieChartBean

/**
 * 自定义饼状图
 *
 * 不要设置wrap_content
 */

class PieChartView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {


    var startAngle = 0f
        @UiThread
        set(value) {
            field = value
            invalidate()
        }
    private val colors = arrayOf(0xff8a2be2, 0xff4682b4, 0xff87ceeb, 0xff7cfc00, 0xffffe4b5, 0xff303F9F)
    var datas = ArrayList<PieChartBean>()
        @UiThread
        set(value) {
            field = value       //更新数据时刷新界面
            invalidate()
        }

    private val radius = 200     //半径
    private lateinit var angles: Array<Float?>

    /**
     * 实现饼状图绘制
     */
    override fun onDraw(canvas: Canvas?) {
        angles = arrayOfNulls(datas.size)   //存已经画的角度

        super.onDraw(canvas)

        canvas?.drawColor(0xff008080.toInt())   //背景绘制

        val itemCount = datas.size
        if (itemCount <= 0) {
            return
        }

        for (i in 0 until itemCount) {
            drawArc(canvas, i)
        }

    }

    private fun drawArc(canvas: Canvas?, i: Int) {
        var oneStartAngle = startAngle
        val paint = Paint()
        paint.isAntiAlias = true
        paint.style = Paint.Style.FILL
        paint.color = colors[i % colors.size].toInt()
        val percent = datas[i].percent
        if (percent <= 0) {
            return
        }
        val sweepAngle = (360f * percent) / 100      //圆弧对应的角度
        angles[i] = sweepAngle

        val rectF = RectF(100f, 100f, 100f + 2 * radius, 100f + 2 * radius)          //在该矩形内

        for (index in 0 until i) {
            oneStartAngle += angles[index]!!
        }
        canvas?.drawArc(rectF, oneStartAngle, sweepAngle, true, paint)     //画扇形
    }
}

PieChartBean:

data class PieChartBean(var title: String, var percent: Float)

使用:

private List<PieChartBean> pieDatas = new ArrayList<>();
private PieChartView pieChartView;
for (int i = 0; i < 6; i++) {
    PieChartBean pieChartBean = new PieChartBean("part" + i + 1, 100 / 6f);
    pieDatas.add(pieChartBean);
    }

    pieChartView = findViewById(R.id.pie_chart);
    pieChartView.setDatas((ArrayList<PieChartBean>) pieDatas);

效果:

android实现简单饼状图绘制