Android自定义叠加柱形图

1.先上效果图


设计图.png

demo效果图.png

2.简介
前几天项目中用到了柱形图,而且是叠加的,找了一些第三方开源库,没有特别合适的,MPAndroidChart能实现这种效果,但是这个库太大了,只为了实现这个效果就引用这个库不太好,就自己写了一个柱形图自定义控件,实现叠加柱形图,适用于简单的几个柱的情况,如果复杂的柱状图建议使用MPAndroidChart和HelloChart这两个开源库。

3.实现原理

demo.png

每个柱形图分为三段,一段是红色框部分称为第二柱,第二段为绿色框部分称为第一柱,第三段为蓝色框部分为数据显示。
首先新建BarChartView继承View,原理就是根据柱形图父控件的高度和y轴的最大值算出柱状图的应有高度,如父控件高度为300,y轴最大值为5k,柱形图的数据为3k,那么柱形图的高度 = 3/5*父控件总高度,在根据柱形图高度计算坐标,画矩形,有了第一柱的坐标再计算第二柱和数据的坐标就简单了。
如下:

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取每个柱的宽度
        int barWidth = getRight() - getLeft();
        //获取总高度
        int totalHeight = canvas.getHeight();
        //画第二柱
        float secondBarHeight = (dataSecond / yMax )* totalHeight;
        float y = totalHeight - secondBarHeight;
        float x = getLeft();
        canvas.drawRect(x,y,x+barWidth,totalHeight,barPaint1);
        //画第一柱
        float firstBarHeght = (dataFirst / yMax )* totalHeight;
        float firstY = totalHeight - firstBarHeght;
        canvas.drawRect(x,firstY,x+barWidth,y,barPaint);
        //画文字
        Rect rect = new Rect();
        textPaint.getTextBounds(String.valueOf(text), 0, String.valueOf(text).length(), rect);
        int w = rect.width();
        int h = rect.height();
        canvas.drawText(String.valueOf(text),(x+barWidth)/2 - w/2,firstY - h/2 - textMagin,textPaint);
    }

4.用法
在xml中声明

 <com.mao.myapp.view.BarChartView
      android:id="@+id/bar_view3"
      android:layout_width="30dp"
      android:layout_height="match_parent"
      app:firstBarColor="@color/colorAccent"
      app:secondeBarColor="@color/colorPrimary"
      app:textColor="@color/colorPrimaryDark"
      app:textSize="12sp"
      app:textMargin="15dp"/>
  android:layout_width="30dp"  //必须为柱形图设置宽度,必须是固定值
  app:firstBarColor="@color/colorAccent" //第一柱的颜色值
  app:secondeBarColor="@color/colorPrimary" //第二柱颜色值
  app:textColor="@color/colorPrimaryDark" //数据的颜色值
  app:textSize="12sp" //数据文字大小
  app:textMargin="15dp" //数据和柱形图距离

在java中设置数据

chartView1 = (BarChartView) findViewById(R.id.bar_view1);
chartView1.setData(1000,800,5000,"1000");
demo.png

找到ChartView控件,调用setData方法设置数据,setData方法的四个参数,第一个参数1000为图中绿色框的数据,第二个参数为图中红色框的数据,第三个参数为y轴的最大值,图中为5k,第四个参数为蓝色框中显示的数据,这样就可以了,用着很简单有没有。至于横纵轴用布局画上去就可以了,我这里用了比重做的。这样这个叠加柱状图的效果就实现了,如果需要动画效果的可以自己加上动画。

5.代码
BarChartView

public class BarChartView extends View {
    Paint textPaint; //文字画笔
    Paint barPaint; //第二柱形图画笔
    Paint barPaint1;//第一柱形图画笔

    int textColor = 0xDDFFFFFF;//文字颜色
    int barColor = 0xDDFF9246; //第二柱形图画笔颜色
    int barColor1 = 0xDDFFAC72;//第一柱形图画笔颜色

    float dataFirst; //第一柱形图数据
    float dataSecond; //第二柱形图数据

    float yMax;//y轴最大数据

    int textMagin = 5; //文字与柱形图距离
    int textSize = 18; //文字大小
    String text; //文字

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

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

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

    private void initPaint(Context context) {
        //获取屏幕宽度
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int mScreenWidth = dm.widthPixels;
        int mScreenHeight = dm.heightPixels;

        //以分辨率为720*1080准,计算宽高比值,根据屏幕比例计算文字大小
        float ratioWidth = (float) mScreenWidth / 720;
        float ratioHeight = (float) mScreenHeight / 1080;
        float ratioMetrics = Math.min(ratioWidth, ratioHeight);
        int textSize = Math.round(this.textSize * ratioMetrics);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(textColor);
        textPaint.setTextSize(textSize);

        barPaint = new Paint();
        barPaint.setAntiAlias(true);
        barPaint.setColor(barColor);

        barPaint1 = new Paint();
        barPaint1.setAntiAlias(true);
        barPaint1.setColor(barColor1);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取每个柱的宽度
        int barWidth = getRight() - getLeft();
        //获取总高度
        int totalHeight = canvas.getHeight();
        //画第二柱
        float secondBarHeight = (dataSecond / yMax )* totalHeight;
        float y = totalHeight - secondBarHeight;
        float x = getLeft();
        canvas.drawRect(x,y,x+barWidth,totalHeight,barPaint1);
        //画第一柱
        float firstBarHeght = (dataFirst / yMax )* totalHeight;
        float firstY = totalHeight - firstBarHeght;
        canvas.drawRect(x,firstY,x+barWidth,y,barPaint);
        //画文字
        Rect rect = new Rect();
        textPaint.getTextBounds(String.valueOf(text), 0, String.valueOf(text).length(), rect);
        int w = rect.width();
        int h = rect.height();
        canvas.drawText(String.valueOf(text),(x+barWidth)/2 - w/2,firstY - h/2 - textMagin,textPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 设置柱型数据
     * @param dataFirst 第一柱的数据值
     * @param dataSecond 第二柱的数据值
     * @param yMax Y轴的最大值
     * @param text 柱上显示的文字
     */
    public void setData(float dataFirst,float dataSecond,float yMax,String text) {
        this.dataSecond = dataSecond;
        this.yMax = yMax;
        this.dataFirst = dataFirst;
        this.text = text;
        invalidate();
    }


    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    public void setBarColor(int barColor) {
        this.barColor = barColor;
    }

    public void setBarColor1(int barColor1) {
        this.barColor1 = barColor1;
    }

    public void setTextMagin(int textMagin) {
        this.textMagin = textMagin;
    }

    public void setTextSize(int textSize) {
        this.textSize = textSize;
    }
}

attr.xml

 <declare-styleable name="BarChartView">
        <attr name="textColor" format="color"/>
        <attr name="firstBarColor" format="color"/>
        <attr name="secondeBarColor" format="color"/>
        <attr name="textMargin" format="dimension"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>

可以直接拷贝过去使用了...

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

推荐阅读更多精彩内容