Android 进阶自定义View(5)图表统计PieChartView圆饼图的实现

今天讲图表统计中比较常用的一个,像支付宝的月账单啥的,都是用圆饼图来做数据统计的,先看一下我最终实现的效果图:


image.png

该效果实际上是两个实心圆叠加后的效果。


image.png
image.png
《一》View实现思路分析:

(1)根据占比集合数据,计算所需绘制的角度,动态设置画笔颜色,drawArc()绘制外圆弧
(2)drawCircle()绘制内圆
(3)确定每块圆饼的小白点的位置
(4)绘制白点的沿线和占比文字

《二》具体实现:

(1)绘制不同颜色的圆饼

   for (int i = 0; i < mRateList.size(); i++) {
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setColor(mColorList.get(i));
//            Log.e("TAG", "startAngle=" + startAngle + "--sweepAngle=" + ((int) (mRateList.get(i) * (360)) - offset));
            canvas.drawArc(rectF, startAngle, (int) (mRateList.get(i) * (360)) , true, mPaint);
            startAngle = startAngle + (int) (mRateList.get(i) * 360);
   }

(2)绘制内圆

  mPaint.setColor(ContextCompat.getColor(mContext, R.color.color_081638));
  canvas.drawCircle(radius + centerPointRadius + (xOffset + yOffset + textRect.width()), radius + centerPointRadius + (xOffset + yOffset + textRect.height()), radius / 1.5f, mPaint);

(3)确定每块圆饼的小白点的位置,通过每段圆饼的起始角度确定该段圆弧的中心点位置。

 private void dealPoint(RectF rectF, float startAngle, float endAngle, List<Point> pointList) {
        Path path = new Path();
        //通过Path类画一个90度(180—270)的内切圆弧路径
        path.addArc(rectF, startAngle, endAngle);

        PathMeasure measure = new PathMeasure(path, false);
//        Log.e("路径的测量长度:", "" + measure.getLength());

        float[] coords = new float[]{0f, 0f};
        //利用PathMeasure分别测量出各个点的坐标值coords
        int divisor = 1;
        measure.getPosTan(measure.getLength() / divisor, coords, null);
//        Log.e("coords:", "x轴:" + coords[0] + " -- y轴:" + coords[1]);
        float x = coords[0];
        float y = coords[1];
        Point point = new Point(Math.round(x), Math.round(y));
        pointList.add(point);
    }

(4)绘制以白点为起点的折线和占比文字。有个细节需要注意一下,绘制折线和比例文字时,每部分沿线和文字的绘制规则不一样,我是按下面的规则处理的:将圆分为四部分,每块区分显示。


image.png
  //折线横向长度
    private int xOffset;
    //折线偏Y方向长度
    private int yOffset;
    private void dealRateText(Canvas canvas, Point point, int position, List<Point> pointList) {
        if (position == 0) {
            lastPoint = pointList.get(0);
        } else {
            lastPoint = pointList.get(position - 1);
        }
        float[] floats = new float[8];
        floats[0] = point.x;
        floats[1] = point.y;
        //右半圆
        if (point.x >= radius + centerPointRadius + (xOffset + yOffset + textRect.width())) {
            mPaint.setTextAlign(Paint.Align.LEFT);
            floats[6] = point.x + xOffset;      
            if (point.y <= radius + centerPointRadius + (xOffset + yOffset + textRect.height())) {
                //右上角
                floats[2] = point.x + yOffset;
                floats[3] = point.y - yOffset;
                floats[4] = point.x + yOffset;
                floats[5] = point.y - yOffset;
                floats[7] = point.y - yOffset;
            } else {
                //右下角
                floats[2] = point.x + yOffset;
                floats[3] = point.y + yOffset;
                floats[4] = point.x + yOffset;
                floats[5] = point.y + yOffset;
                floats[7] = point.y + yOffset;
            }
            //左半圆
        } else {
            mPaint.setTextAlign(Paint.Align.RIGHT);
            floats[6] = point.x - xOffset;
            //防止相邻的圆饼绘制的文字重叠显示
            if (point.y <= radius + centerPointRadius) {
                //左上角
                floats[2] = point.x - yOffset;
                floats[3] = point.y - yOffset;
                floats[4] = point.x - yOffset;
                floats[5] = point.y - yOffset;
                floats[7] = point.y - yOffset;
            } else {
                //左下角
                floats[2] = point.x - yOffset;
                floats[3] = point.y + yOffset;
                floats[4] = point.x - yOffset;
                floats[5] = point.y + yOffset;
                floats[7] = point.y + yOffset;
            }
        }
        //根据每块的颜色,绘制对应颜色的折线
//        mPaint.setColor(mRes.getColor(colorList.get(position)));
        mPaint.setColor(ContextCompat.getColor(mContext, R.color.color_b69b4f));
        //画圆饼图每块边上的折线
        canvas.drawLines(floats, mPaint);
        mPaint.setStyle(Paint.Style.STROKE);
        //绘制显示的文字,需要根据类型显示不同的文字
        if (mRateList.size() > 0) {
            //Y轴:+ textRect.height() / 2 ,相对沿线居中显示
            canvas.drawText(getFormatPercentRate(mRateList.get(position) * 100) + "%", floats[6], floats[7] + textRect.height() / 2, mPaint);
        }
    }

完整代码:

package com.example.jojo.learn.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import com.example.jojo.learn.R;
import com.example.jojo.learn.utils.DP2PX;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by JoJo on 2018/8/6.
 * wechat:18510829974
 * description: 饼状图
 */

public class PieView extends View {
    private Context mContext;
    private Paint mPaint;
    //每块占比的绘制的颜色
    private List<Integer> mColorList = new ArrayList<>();
    //圆弧占比的集合
    private List<Float> mRateList = new ArrayList<>();
    //是否展示文字
    private boolean isShowRateText;
    //圆弧半径
    private float radius;
    private int startAngle = 0;
    //不同色块之间是否需要空隙offset
    private int offset = 0;
    //圆弧中心点小圆点的圆心半径
    private int centerPointRadius;
    private float showRateSize;
    private Rect textRect;
    //折线横向长度
    private int xOffset;
    //折线偏Y方向长度
    private int yOffset;
    private float mChangeAngle;
    private boolean isAnimation;
    private int sign = 0;

    public PieView(Context context) {
        this(context, null);
    }

    public PieView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        init();

        initData();
    }

    private void initData() {

        float[] rate = {30f, 40f, 15f, 15f};
        int[] colors = {Color.RED, Color.BLUE, Color.YELLOW, Color.GRAY};
        for (int i = 0; i < rate.length; i++) {
            mRateList.add(rate[i] / 100);
            mColorList.add(colors[i]);
        }

        textRect = new Rect();
        if (mRateList.size() > 0) {
            mPaint.getTextBounds((mRateList.get(0) + "%"), 0, (mRateList.get(0) + "%").length(), textRect);
        }
    }

    private void init() {
        radius = DP2PX.dip2px(mContext, 80);
        centerPointRadius = DP2PX.dip2px(mContext, 2);
        xOffset = DP2PX.dip2px(mContext, 20);
        yOffset = DP2PX.dip2px(mContext, 5);
        showRateSize = DP2PX.dip2px(mContext, 10);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextSize(showRateSize);

        if (mRateList.size() > 0) {
            textRect = new Rect();
            mPaint.getTextBounds((mRateList.get(0) + "%"), 0, (mRateList.get(0) + "%").length(), textRect);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.AT_MOST) {
            //边沿线和文字所占的长度:(xOffset + yOffset + textRect.width())
            heightSize = (int) (radius * 2) + 2 * centerPointRadius + getPaddingLeft() + getPaddingRight() + (xOffset + yOffset + textRect.height()) * 2;
        }
        if (widthMode == MeasureSpec.AT_MOST) {

            widthSize = (int) (radius * 2) + 2 * centerPointRadius + getPaddingLeft() + getPaddingRight() + (xOffset + yOffset + textRect.width()) * 2;
        }
        //保存测量结果
        setMeasuredDimension(widthSize, heightSize);
    }

    private int paintPosition;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //(1)绘制圆饼
        RectF rectF = new RectF(0 + centerPointRadius + (xOffset + yOffset + textRect.width()), 0 + centerPointRadius + (xOffset + yOffset + textRect.height()), 2 * radius + centerPointRadius + (xOffset + yOffset + textRect.width()), 2 * radius + centerPointRadius + (xOffset + yOffset + textRect.height()));
        List<Point> mPointList = new ArrayList<>();

        for (int i = 0; i < mRateList.size(); i++) {
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setColor(mColorList.get(i));
//            Log.e("TAG", "startAngle=" + startAngle + "--sweepAngle=" + ((int) (mRateList.get(i) * (360)) - offset));
            canvas.drawArc(rectF, startAngle, (int) (mRateList.get(i) * (360)) - offset, true, mPaint);

            //(2)处理每块圆饼弧的中心点,绘制折线,显示对应的文字
            if (isShowRateText) {
                dealPoint(rectF, startAngle, (mRateList.get(i) * 360 - offset) / 2, mPointList);
                Point point = mPointList.get(i);
                mPaint.setColor(Color.WHITE);//点的绘制的颜色
                canvas.drawCircle(point.x, point.y, centerPointRadius, mPaint);
                dealRateText(canvas, point, i, mPointList);
            }
            startAngle = startAngle + (int) (mRateList.get(i) * 360);
        }
        //(3)绘制内部中空的圆
        mPaint.setColor(ContextCompat.getColor(mContext, R.color.color_081638));
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(radius + centerPointRadius + (xOffset + yOffset + textRect.width()), radius + centerPointRadius + (xOffset + yOffset + textRect.height()), radius / 1.5f, mPaint);

    }

    private Point lastPoint;

    private void dealRateText(Canvas canvas, Point point, int position, List<Point> pointList) {
        if (position == 0) {
            lastPoint = pointList.get(0);
        } else {
            lastPoint = pointList.get(position - 1);
        }
        float[] floats = new float[8];
        floats[0] = point.x;
        floats[1] = point.y;
        //右半圆
        if (point.x >= radius + centerPointRadius + (xOffset + yOffset + textRect.width())) {
            mPaint.setTextAlign(Paint.Align.LEFT);
            floats[6] = point.x + xOffset;
            //防止相邻的圆饼绘制的文字重叠显示
//            if (lastPoint != null) {
//                int absX = Math.abs(point.x - lastPoint.x);
//                int absY = Math.abs(point.y - lastPoint.y);
//                if (absX > 0 && absX < 20 && absY > 0 && absY < 20) {
//                    floats[6] = point.x + xOffset - textRect.width() / 2;
//                    Log.e("TAG", "右半圆");
//                } else {
//                    floats[6] = point.x + xOffset;
//                }
//            } else {
//                floats[6] = point.x + xOffset;
//            }
            if (point.y <= radius + centerPointRadius + (xOffset + yOffset + textRect.height())) {
                //右上角
                floats[2] = point.x + yOffset;
                floats[3] = point.y - yOffset;
                floats[4] = point.x + yOffset;
                floats[5] = point.y - yOffset;
                floats[7] = point.y - yOffset;
            } else {
                //右下角
                floats[2] = point.x + yOffset;
                floats[3] = point.y + yOffset;
                floats[4] = point.x + yOffset;
                floats[5] = point.y + yOffset;
                floats[7] = point.y + yOffset;
            }
            //左半圆
        } else {
            mPaint.setTextAlign(Paint.Align.RIGHT);
            floats[6] = point.x - xOffset;
            //防止相邻的圆饼绘制的文字重叠显示
//            if (lastPoint != null) {
//                int absX = Math.abs(point.x - lastPoint.x);
//                int absY = Math.abs(point.y - lastPoint.y);
//                if (absX > 0 && absX < 20 && absY > 0 && absY < 20) {
//                    floats[6] = point.x - xOffset - textRect.width() / 2;
//                    Log.e("TAG", "左半圆");
//                } else {
//                    floats[6] = point.x - xOffset;
//                }
//            } else {
//                floats[6] = point.x - xOffset;
//            }
            if (point.y <= radius + centerPointRadius) {
                //左上角
                floats[2] = point.x - yOffset;
                floats[3] = point.y - yOffset;
                floats[4] = point.x - yOffset;
                floats[5] = point.y - yOffset;
                floats[7] = point.y - yOffset;
            } else {
                //左下角
                floats[2] = point.x - yOffset;
                floats[3] = point.y + yOffset;
                floats[4] = point.x - yOffset;
                floats[5] = point.y + yOffset;
                floats[7] = point.y + yOffset;
            }
        }
        //根据每块的颜色,绘制对应颜色的折线
//        mPaint.setColor(mRes.getColor(colorList.get(position)));
        mPaint.setColor(ContextCompat.getColor(mContext, R.color.color_b69b4f));
        //画圆饼图每块边上的折线
        canvas.drawLines(floats, mPaint);
        mPaint.setStyle(Paint.Style.STROKE);
        //绘制显示的文字,需要根据类型显示不同的文字
        if (mRateList.size() > 0) {
            //Y轴:+ textRect.height() / 2 ,相对沿线居中显示
            canvas.drawText(getFormatPercentRate(mRateList.get(position) * 100) + "%", floats[6], floats[7] + textRect.height() / 2, mPaint);
        }
    }

    private void dealPoint(RectF rectF, float startAngle, float endAngle, List<Point> pointList) {
        Path path = new Path();
        //通过Path类画一个90度(180—270)的内切圆弧路径
        path.addArc(rectF, startAngle, endAngle);

        PathMeasure measure = new PathMeasure(path, false);
//        Log.e("路径的测量长度:", "" + measure.getLength());

        float[] coords = new float[]{0f, 0f};
        //利用PathMeasure分别测量出各个点的坐标值coords
        int divisor = 1;
        measure.getPosTan(measure.getLength() / divisor, coords, null);
//        Log.e("coords:", "x轴:" + coords[0] + " -- y轴:" + coords[1]);
        float x = coords[0];
        float y = coords[1];
        Point point = new Point(Math.round(x), Math.round(y));
        pointList.add(point);
    }

    public void updateDate(List<Float> rateList, List<Integer> colorList, boolean isShowRateText) {
        this.isShowRateText = isShowRateText;
        this.mRateList = rateList;
        this.mColorList = colorList;
        init();
        invalidate();
    }

    /**
     * 获取格式化的保留两位数的数
     */
    public String getFormatPercentRate(float dataValue) {
        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        return decimalFormat.format(dataValue);
    }


}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容

  • 【Android 自定义View之绘图】 基础图形的绘制 一、Paint与Canvas 绘图需要两个工具,笔和纸。...
    Rtia阅读 11,643评论 5 34
  • 最近感觉人际关系有明显好转,持续清理,谢谢你,我爱你! 我发现自己的新功课,是当我看到身边相对比较亲近的朋友,和别...
    佩盈阅读 341评论 0 2
  • 小时候, 每次生病首当其冲的几乎是屁股, 那泛着寒光细长的针, 总能激起孩童的泪腺飙升, 哇哇大哭,抑或抽抽噎噎,...
    井溢阅读 275评论 3 3
  • 今天一早原本计划去宝安染发,为了周六拍婚纱照,但姐姐的一个电话让我打消了这个念头,再加上自己本来就不舍得将自己黑头...
    蘭Zena阅读 104评论 0 0
  • 无意间从一本具有伤感文字的书籍中滑落出一个泛黄书签,不是写有古文诗句的正方纸片,也不是绘有诗情画意的风景佳图。而是...
    颜贵人阅读 305评论 0 1