自定义统计柱状图

虽然开源了,但是转载本文需要经过本人的同意,谢谢!
直接上图

barGraph.gif

想达到下面的效果,怎么去处理?下面一步步去分析。
整体是5个类似的圆柱进行的一个动画效果。第一时间想的比较复制,由于给到的设计图每个圆柱下面还有一个TextView,我是在画布里面把5个圆柱都画出来,包括下面的文字处理,比较复杂,走了不少弯路,老大后来说直接画一个,结合RecycleView就能实现,试了一下,效果不错。
现在就抛开动画效果,对单一的一个进行分析。我们可以看出,静态的图片当中是有几个部分。1.圆柱2.圆环,包括虚线部分,还有实线部分,3.圆。其中圆柱部分可以看成一个矩形,上边的一个椭圆,下面部分一个半圆。
item.jpg
,
item2.jpeg
(画的比较丑,将就将就)。下面就是基础图形的绘制,如果有不清楚的,可以参考下面这个地址,我觉得写的非常好。https://github.com/GcsSloop/AndroidNote/blob/master/CustomView/Advance/%5B02%5DCanvas_BasicGraphics.md
下面直接上代码:

public class BarGraphView extends View {
    private float totalWeight;
    private Paint dotLinePaint;
    private Paint circleLinePaint;
    private Paint circleFillPaint;
    private Paint columnPaint;
    private Paint columnBottomPaint;
    private Paint columnTopPaint;
    private Paint numberPaint;

    private int barGraphViewWidth = 1080;
    private int barGraphViewHeight = 1920;

    private int ovalWidth = 120;
    private int ovalHeight = 60;

    private int outerInnerWidth = 10;
    private int outerInnerHeight = 10;

    private int numberTextSize = 30;
    private int maxHeight;
    private float maxNumber = 5000;

    private int startColor = 0xD900D061;
    private int endColor = 0xFF2DE526;
    private int colorTransEnd = 0xE92DE526;
    private int numberTextColor = Color.WHITE;
    private int marginBottom = 30;
    private int lineStrokeWidth = 3;

    private float progress;
    private boolean hasAnimation;

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

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

    public BarGraphView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private void initPaint() {
        dotLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        dotLinePaint.setStyle(Paint.Style.STROKE);
        dotLinePaint.setStrokeWidth(2f);
        //先画长度为3的实线,再间隔长度为2的空白
        dotLinePaint.setPathEffect(new DashPathEffect(new float[]{3, 2}, 0));


        columnPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        columnPaint.setStrokeWidth(20f);
        columnPaint.setStyle(Paint.Style.FILL);


        columnBottomPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        columnBottomPaint.setStyle(Paint.Style.FILL);

        columnTopPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        columnTopPaint.setStrokeWidth(20f);
        columnTopPaint.setStyle(Paint.Style.FILL);

        circleLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circleLinePaint.setStrokeWidth(lineStrokeWidth);
        circleLinePaint.setStyle(Paint.Style.STROKE);

        circleFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circleFillPaint.setStrokeWidth(lineStrokeWidth);
        circleFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        numberPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        numberPaint.setStyle(Paint.Style.FILL);
        numberPaint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.translate(lineStrokeWidth, barGraphViewHeight - ovalHeight - marginBottom);
        float number = totalWeight;
        float currentHeight = number / maxNumber * maxHeight;
        drawColumn(canvas, currentHeight * progress, currentHeight);
        drawNumberText(canvas, totalWeight, currentHeight * progress + ovalHeight / 2);
        canvas.restore();
    }

    private void drawColumn(Canvas canvas, float currentHeight, float finalHeight) {
        columnTopPaint.setColor(endColor);
        columnBottomPaint.setColor(startColor);
        dotLinePaint.setColor(endColor);
        circleLinePaint.setColor(endColor);
        circleFillPaint.setColor(endColor);

        columnPaint.setShader(new LinearGradient(ovalWidth / 2,
                ovalHeight / 2, ovalWidth / 2,
                -currentHeight + ovalHeight / 2, new int[]{startColor,
                colorTransEnd}, new float[]{0.2f, 0.8f}, LinearGradient.TileMode.CLAMP));

        RectF dotRectF = new RectF(outerInnerWidth, outerInnerHeight, ovalWidth - outerInnerWidth, ovalHeight - outerInnerHeight);
        canvas.drawOval(dotRectF, dotLinePaint);

        //从某个角度开始,扫过多少角度
        RectF ArcRectF = new RectF(0, 0, ovalWidth, ovalHeight);
        canvas.drawArc(ArcRectF, 60, -310, false, circleLinePaint);

        /*椭圆上的特殊点 坐标
        13*pow(x,2)=4*pow(b,2)
        以0,0为原点计算值*/
        float x = (float) Math.sqrt(Math.pow(ovalHeight, 2) / 13);
        float y = (float) (Math.sqrt(Math.pow(ovalHeight, 2) / 13) * Math.sqrt(3));
        x = ovalWidth / 2 - x;
        y = ovalHeight / 2 + y;
        canvas.drawCircle(x, y, 5, circleFillPaint);

        canvas.drawRect(outerInnerWidth * 2, -currentHeight + ovalHeight / 2, ovalWidth - outerInnerWidth * 2, ovalHeight / 2, columnPaint);

        RectF rectFBottom = new RectF(outerInnerWidth * 2, outerInnerHeight * 2, ovalWidth - outerInnerWidth * 2, ovalHeight - outerInnerHeight * 2);
        canvas.drawArc(rectFBottom, 0, 180, false, columnBottomPaint);

        RectF rectFTop = new RectF(outerInnerWidth * 2, outerInnerHeight * 2 - currentHeight, ovalWidth - outerInnerWidth * 2, ovalHeight - outerInnerHeight * 2 - currentHeight);
        canvas.drawOval(rectFTop, columnTopPaint);
    }

    /**
     * 画文字数量
     *
     * @param numberText
     */
    private void drawNumberText(Canvas canvas, float numberText, float columnHeightWithoutBottom) {
        numberPaint.setColor(numberTextColor);
        RectF numberRectF = new RectF(0, -columnHeightWithoutBottom + ovalHeight / 2, ovalWidth, -columnHeightWithoutBottom + ovalHeight / 2);
        Paint.FontMetrics fontMetrics = numberPaint.getFontMetrics();
        float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        float baseline = numberRectF.centerY() + distance;
        float currentData = numberText / 1000 * progress;
        DecimalFormat decimalFormat = new DecimalFormat("0.000");
        String data = decimalFormat.format(currentData);
        if (progress == 1) {
            canvas.drawText(trimDotEndZero(data), numberRectF.centerX(), baseline, numberPaint);
        } else {
            canvas.drawText(data, numberRectF.centerX(), baseline, numberPaint);
        }
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        setMeasuredDimension(barGraphViewWidth, barGraphViewHeight);
    }

    /**
     * 设置虚线样式
     *
     * @param dashPathEffect
     */
    public BarGraphView setDotLineStyle(DashPathEffect dashPathEffect) {
        dotLinePaint.setPathEffect(dashPathEffect);
        return this;
    }

    public BarGraphView setMaxNumber(float maxNumber) {
        this.maxNumber = maxNumber;
        return this;
    }

    public void setLineStrokeWidth(int lineStrokeWidth) {
        this.lineStrokeWidth = lineStrokeWidth;
    }

    /**
     * 必须设置
     *
     * @param barGraphViewHeight
     * @return
     */
    public BarGraphView setBarGraphViewHeight(int barGraphViewHeight) {
        this.barGraphViewHeight = barGraphViewHeight;
        return this;
    }

    /**
     * 长宽比2:1方便计算
     * ovalHeight必须为2的整数,不然会有1个像素误差
     * 那么计算值的时候ovalWidth为4的整数倍
     *
     * @param ovalWidth
     * @return
     */
    public BarGraphView setOvalWidthAndHeight(int ovalWidth) {
        this.ovalWidth = ovalWidth / 4 * 4;
        this.ovalHeight = this.ovalWidth / 2;
        return this;
    }


    public BarGraphView setNumberTextSize(int numberTextSize) {
        this.numberTextSize = numberTextSize;
        numberPaint.setTextSize(numberTextSize);
        return this;
    }


    public BarGraphView hasAnimation(boolean b) {
        hasAnimation = b;
        return this;
    }

    public BarGraphView setStartColor(int startColor) {
        this.startColor = startColor;
        return this;
    }

    public BarGraphView setEndColor(int endColor) {
        this.endColor = endColor;
        return this;
    }

    public BarGraphView setColorTransEnd(int colorTransEnd) {
        this.colorTransEnd = colorTransEnd;
        return this;
    }

    public BarGraphView setNumberTextColor(int numberTextColor) {
        this.numberTextColor = numberTextColor;
        numberPaint.setColor(this.numberTextColor);
        return this;
    }

    /**
     * 最终调用方法
     */
    public void setTotalWeight(float totalWeight) {
        this.totalWeight = totalWeight;
        progress = 0;
        if (barGraphViewHeight == 0) {
            throw new RuntimeException("barGraphViewHeight can not be zero");
        }
        barGraphViewWidth = ovalWidth + lineStrokeWidth * 2;
        maxHeight = barGraphViewHeight - ovalHeight - numberTextSize - marginBottom;
        if (hasAnimation) {
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(progress, 1);
            valueAnimator.setDuration(2000);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator1) {
                    float value = (float) valueAnimator1.getAnimatedValue();
                    progress = value;
                    invalidate();
                }
            });
            valueAnimator.setInterpolator(new DecelerateInterpolator());
            valueAnimator.start();
        }
    }

    private String trimDotEndZero(String oriStr) {
        if (oriStr.indexOf(".") > 0) {
            //去掉多余的0
            oriStr = oriStr.replaceAll("0+?$", "");
            //如最后一位是.则去掉
            oriStr = oriStr.replaceAll("[.]$", "");
        }
        return oriStr;
    }

其中加了颜色渐变,startColor,endColor加以设置。具体的XML,还有RecycleView的Adapter关键代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.hwariot.weightbridge.widget.bargraph.BarGraphView
        android:id="@+id/item_statistics_BarGraphView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"

        />

    <TextView
        android:id="@+id/item_statistics_name_TextView"
        android:layout_width="@dimen/dimen_size_50"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ellipsize="end"
        android:maxLines="3"
        android:text="上海某某有限公司"
        android:gravity="center_horizontal"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_10" />
</LinearLayout>
holder.barGraphView
                .setNumberTextSize(UnitFormatUtil.dp2px(12))
                .setOvalWidthAndHeight(UnitFormatUtil.dp2px(50))
                .setBarGraphViewHeight(UnitFormatUtil.dp2px(165))
                .setStartColor(colorStartArray[position])
                .setEndColor(colorEndArray[position])
                .setColorTransEnd(colorTransEndArray[position])
                .setMaxNumber(maxNumber)
                .hasAnimation(true)
                .setTotalWeight(supplierBean.getTotalWeight());

接下来看下增加渐变和结合textView的最终样子
barGraph2.gif

写的一般,仅供参考。

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

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,654评论 2 59
  • 何妨饮罢更颠狂,几许风骚即兴扬。 相与落花繁酒梦,共泥明月醉诗肠。 流连自觉思心远,谩忆才知归路长。 应惜人间好光...
    雪窗_武立之阅读 441评论 2 8
  • 六点钟醒了,躺着听听新闻,慢慢就毫无睡意了,索性起来洗澡做早餐,在周六这个美好的早晨,喵喵知道自己又被昨天的事情...
    像疯子那般追逐阅读 186评论 0 0
  • 《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代...
    fancy_boy_石嘉成阅读 374评论 0 0