柱状对比图可滑动

自定义view

public class BarGraphView extends View {
    private Context mContext;
    /**
     * 柱状图的宽度
     */
    private float mLineWidth;
    /**
     * 柱状图之间的间隔
     */
    private float mLineSpaceWidth;
    /**
     * 柱状图的颜色
     */
    private int barGraphBgColor;
    /**
     * X轴字体的大小
     */
    private float mXTextSize;
    /**
     * Y轴的字体大小
     */
    private float mYTextSize;
    /**
     * xy轴线和字体的颜色
     */
    private int mXYBGColor;
    /**
     * 柱状图执行动画的长度
     */
    private Integer duration;
    /**
     * 是否显示X轴的文字
     */
    private boolean isShowXText;
    /**
     * 是否显示Y轴的文字
     */
    private boolean isShowYText;

    /**
     * 柱状图的画笔
     */
    private Paint mBarGraphPaint;
    /**
     * 柱状图上面字的画笔
     */
    private Paint mBarGraphTextPaint;
    /**
     * X轴的文字画笔
     */
    private Paint mXTextPaint;
    /**
     * Y轴的文字画笔
     */
    private Paint mYTextPaint;
    /**
     * XY轴的坐标画笔
     */
    private Paint mXYLinePaint;
    /**
     * 当前柱状图的最大高度
     */
    private int maxHeight;
    /**
     * 实际高度
     */
    private int heightMeasureSpec;
    /**
     * 实际宽度
     */
    private int widthMeasureSpec;
    /**
     * 圆柱占用的高度
     */
    private float bottomHeight;

    //保存柱状图的数据
    private int[][] barGraphDataList;
    //保存柱状图的颜色
    private int[] barGraphColorList;
    //保存柱状图X轴信息
    private String[] barGraphTextList;
    //Y轴线离左边的距离,以便绘制Y轴数字
    private float mLeftYWidth;
    //X轴线离底部的距离,以便绘制X轴的文字
    private float mBottomXWidth;
    private Bitmap mBitmap;


    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);
        this.mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BarGraphView);
        //柱状图的宽度
        mLineWidth = typedArray.getDimension(R.styleable.BarGraphView_bar_graph_width, dip2px(10));
        //柱状图之间的间隔
        mLineSpaceWidth = typedArray.getDimension(R.styleable.BarGraphView_bar_graph_distance, dip2px(20));
        //柱状图的颜色
        barGraphBgColor = typedArray.getColor(R.styleable.BarGraphView_bar_graph_bg_color, Color.BLUE);
        //X轴字体大小
        mXTextSize = typedArray.getDimension(R.styleable.BarGraphView_bar_graph_x_textSize, sp2px(12));
        //y轴字体大小
        mYTextSize = typedArray.getDimension(R.styleable.BarGraphView_bar_graph_y_textSize, sp2px(12));
        //xy轴的颜色
        mXYBGColor = typedArray.getColor(R.styleable.BarGraphView_bar_graph_xy_line_text_color, context.getResources().getColor(R.color.text_color_3));
        //执行动画的时间
        duration = typedArray.getInteger(R.styleable.BarGraphView_bar_graph_animation_duration, 1000);
        isShowXText = typedArray.getBoolean(R.styleable.BarGraphView_bar_graph_isShow_X_text, true);
        isShowYText = typedArray.getBoolean(R.styleable.BarGraphView_bar_graph_isShow_Y_text, true);
        /**
         * 系统使用一个arraypool池来存放typearray 用完及时销毁以便复用
         * */
        typedArray.recycle();
        initView();
    }

    /**
     * 初始化画笔
     */
    private void initView() {
        mBarGraphPaint = new Paint();
        mBarGraphPaint.setStrokeWidth(mLineWidth);
        mBarGraphPaint.setAntiAlias(true);

        mBarGraphTextPaint = new Paint();
        mBarGraphTextPaint.setStrokeWidth(dip2px(8));
        mBarGraphTextPaint.setTextSize(sp2px(12f));
//        mBarGraphTextPaint.setColor(getResources().getColor(R.color.circle_6));
        mBarGraphTextPaint.setAntiAlias(true);

        mXTextPaint = new Paint();
        mXTextPaint.setStrokeWidth(3);
        mXTextPaint.setColor(mXYBGColor);
        mXTextPaint.setTextSize(mXTextSize);
        mXTextPaint.setAntiAlias(true);

        mYTextPaint = new Paint();
        mYTextPaint.setStrokeWidth(3);
        mYTextPaint.setColor(mXYBGColor);
        mYTextPaint.setTextSize(mYTextSize);
        mYTextPaint.setAntiAlias(true);

        mXYLinePaint = new Paint();
        mXYLinePaint.setStrokeWidth(2);
        mXYLinePaint.setColor(getResources().getColor(R.color.paint_color6));
        mXYLinePaint.setAntiAlias(true);

        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
    }

    /**
     * 测量宽度
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureWidth(heightMeasureSpec);
    }

    /**
     * 长度可能超出屏幕范围
     */
    private void measureWidth(int heightMeasureSpec) {
        if (barGraphDataList != null && barGraphDataList.length > 0) {
            widthMeasureSpec = (int) (mLineSpaceWidth * (barGraphDataList[0].length + 1) + mLineWidth * barGraphDataList.length * barGraphDataList[0].length) + dip2px(200);
        }
        this.heightMeasureSpec = MeasureSpec.getSize(heightMeasureSpec);
        //左边字体的长度
        widthMeasureSpec += mLeftYWidth + dip2px(10);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        measureWidth(h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        bottomHeight = heightMeasureSpec - mBottomXWidth;
        if (barGraphDataList == null || barGraphDataList.length <= 0)
            return;

        //给XY轴坐标写字
        drawXYText(canvas);
        //画柱状图
        drawBarGraph(canvas);
    }

    //给Y轴和X轴写相应的文字
    private void drawXYText(Canvas canvas) {
        if (isShowYText) {
            //Y轴写字
            for (int i = 0; i <= 5; i++) {
                float startY = bottomHeight - bottomHeight * 0.9f / maxHeight * maxHeight / 5 * i;
                canvas.drawLine(dip2px(10) + mLeftYWidth, startY, widthMeasureSpec - 10, startY, mXYLinePaint);
                String text = maxHeight / 5 * i + "";
                String format = (Double.valueOf(text) / 100) + "";
                float width = mYTextPaint.measureText(format);
                Paint.FontMetricsInt fontMetricsInt = mYTextPaint.getFontMetricsInt();
                float dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
                canvas.drawText(format, (int) (dip2px(10) + mLeftYWidth - width + dip2px(5)), startY + dy, mYTextPaint);
            }
        }
        if (!isShowXText) {
            return;
        }
        //X轴写字
        if (barGraphTextList != null && barGraphTextList.length > 0) {
            for (int i = 0; i < barGraphTextList.length; i++) {
                float startX = mLineSpaceWidth * (i + 1) + mLineWidth * barGraphDataList.length * i + mLeftYWidth + dip2px(10);
                //中间有一个间隔
                startX = startX + (mLineWidth * barGraphDataList.length) * 1.0f / 2;
                float textWidth = mXTextPaint.measureText(barGraphTextList[i]);
                canvas.drawText(barGraphTextList[i], startX - textWidth / 2 + dip2px(10), heightMeasureSpec - dip2px(5), mXTextPaint);
            }
        }
    }


    //画柱状图
    private void drawBarGraph(Canvas canvas) {
        if (barGraphDataList != null && barGraphDataList.length > 0) {
            for (int i = 0; i < barGraphDataList[0].length; i++) {
                float startX = mLineSpaceWidth * (i + 1) + mLineWidth * barGraphDataList.length * i + mLeftYWidth + dip2px(10) + mLineWidth / 2;
                int index = 0;
                while (index < barGraphDataList.length) {
                    if (barGraphColorList != null && barGraphColorList.length > index) {
                        mBarGraphPaint.setColor(barGraphColorList[index]);
                        mBarGraphTextPaint.setColor(barGraphColorList[index]);
                    } else {
                        mBarGraphPaint.setColor(barGraphBgColor);
                        mBarGraphTextPaint.setColor(barGraphBgColor);
                    }

                    float stopY = bottomHeight * 0.9f / maxHeight * barGraphDataList[index][i];

//                    canvas.drawLine(startX, bottomHeight, startX, bottomHeight - stopY, mBarGraphPaint);
                    RectF rectF = new RectF(startX, bottomHeight, startX + mLineWidth, bottomHeight - stopY);
                    Path path = new Path();
                    //float数组中4个角分别是左上、右上、右下、左下
                    path.addRoundRect(rectF, new float[]{100, 100, 100, 100, 0, 0, 0, 0}, Path.Direction.CCW);
                    canvas.drawPath(path, mBarGraphPaint);
//                    canvas.drawRoundRect(rectF, 100, 100, mBarGraphPaint);

//                    canvas.drawBitmap(mBitmap, startX - dip2px(15), bottomHeight - stopY - mBitmap.getHeight() + 20, mBarGraphPaint);


                    String text = String.valueOf(barGraphDataList[index][i]);
                    String format = (Double.valueOf(text) / 100) + "";
                    float textWidth = mBarGraphTextPaint.measureText(format, 0, format.length());
//                    canvas.drawText(format, startX - textWidth / 2 + mLineWidth / 2, bottomHeight - stopY - mBitmap.getHeight() / 2+20, mBarGraphTextPaint);
                    canvas.drawText(format, startX - textWidth / 2 + mLineWidth / 2, bottomHeight - stopY - 10, mBarGraphTextPaint);
                    startX += mLineWidth;
                    index++;
                }
            }
        }
    }

    /**
     * 传进来的数组要求保持数组长度一致
     */
    public void setBarGraphData(@NonNull int[][] barGraphDataList, int[] barGraphColorList, String[] barGraphTextList) {
        maxHeight=0;
        this.barGraphDataList=null;
        this.barGraphColorList=null;
        this.barGraphTextList=null;
        this.barGraphDataList = barGraphDataList;
        this.barGraphColorList = barGraphColorList;
        this.barGraphTextList = barGraphTextList;

        //计算出最高的坐标
        for (int i = 0; i < barGraphDataList.length; i++) {
            for (int j = 0; j < barGraphDataList[i].length; j++) {
                if (maxHeight < barGraphDataList[i][j]) {
                    maxHeight = barGraphDataList[i][j];
                }
            }
        }
        while (maxHeight % 5 != 0) {
            maxHeight++;
        }
        if (barGraphTextList != null && barGraphTextList.length > 0) {
            isShowXText = true;
        }
        if (isShowYText) {
            mLeftYWidth = mYTextPaint.measureText(String.valueOf(maxHeight));
        }
        mBottomXWidth = dip2px(10);
        if (isShowXText) {
            Paint.FontMetrics fontMetrics = mXTextPaint.getFontMetrics();
            mBottomXWidth += ((fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom) * 2;
        }
        measureWidth(heightMeasureSpec);

        invalidate();
    }

    /**
     * 不需要显示XY轴文字
     */
    public void setIsShowXYText(boolean isShowXText, boolean isShowYText) {
        this.isShowXText = isShowXText;
        this.isShowYText = isShowYText;
    }

    /**
     * 设置圆柱的宽度
     */
    public void setBarGraphWidth(int width) {
        this.mLineWidth = dip2px(width);
        measureWidth(heightMeasureSpec);
        mBarGraphPaint.setStrokeWidth(mLineWidth);
        invalidate();
    }

    /**
     * 设置圆柱之间的间隔
     */
    public void setBarGraphDistance(int distance) {
        this.mLineSpaceWidth = dip2px(distance);
        measureWidth(heightMeasureSpec);
        invalidate();
    }

    /**
     * 设置X轴文字大小
     */
    public void setXTextSize(float textSize) {
        this.mXTextSize = sp2px(textSize);
        mXTextPaint.setTextSize(mXTextSize);
        invalidate();
    }

    /**
     * 设置Y轴的文字大小
     */
    public void setYTextSize(float textSize) {
        this.mYTextSize = sp2px(textSize);
        mYTextPaint.setTextSize(mYTextSize);
        invalidate();
    }

    //开始动画
    public void startAnimation(int... duration) {
        if (barGraphDataList == null || barGraphDataList.length <= 0)
            return;
        AnimatorSet animationSet = new AnimatorSet();
        for (int i = 0; i < barGraphDataList.length; i++) {
            final int finalI = i;
            for (int j = 0; j < barGraphDataList[i].length; j++) {
                ValueAnimator animator = ValueAnimator.ofInt(0, barGraphDataList[i][j]);
                final int finalJ = j;
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        barGraphDataList[finalI][finalJ] = (int) animation.getAnimatedValue();
                        invalidate();
                    }
                });
                animationSet.playTogether(animator);
            }
        }
        animationSet.setInterpolator(new DecelerateInterpolator());
        animationSet.setDuration(duration != null ? duration[0] : this.duration);
        animationSet.start();
    }

    /**
     * sp转px
     */
    public int sp2px(float spValue) {
        final float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * dp转px
     */
    public int dip2px(float dpValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

BarGraphView styleable 文件

 <declare-styleable name="BarGraphView">
        <!--柱状图的颜色-->
        <attr name="bar_graph_bg_color" format="color" />
        <!--柱状图之间的间隔-->
        <attr name="bar_graph_distance" format="dimension" />
        <!--柱状图的宽度-->
        <attr name="bar_graph_width" format="dimension" />
        <!-- xy轴线和文字的颜色-->
        <attr name="bar_graph_xy_line_text_color" format="color" />
        <!--x轴文字的大小-->
        <attr name="bar_graph_x_textSize" format="dimension" />
        <!--y轴文字大小-->
        <attr name="bar_graph_y_textSize" format="dimension" />
        <!--动画播放时长-->
        <attr name="bar_graph_animation_duration" format="integer" />
        <!--是否显示X轴的文字-->
        <attr name="bar_graph_isShow_X_text" format="boolean"/>
        <!--是否显示Y轴的文字-->
        <attr name="bar_graph_isShow_Y_text" format="boolean"/>

    </declare-styleable>

布局文件

   <com.dingler.water.cloud.functionbag.drainersmanager.watermonitoring.analysis.view.zz.BarGraphView
                            android:id="@+id/bargraphview1"
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp_200"
                            app:bar_graph_bg_color="#ff6547"
                            app:bar_graph_distance="10dp"
                            app:bar_graph_width="20dp"
                            app:bar_graph_x_textSize="15sp"
                            app:bar_graph_y_textSize="14sp" />

引用

 private void initFacilityYearData(int position) {
//两组数据
        int[][] data1 = new int[2][12];
        int[][] data2 = new int[2][12];
        for (int i = 0; i < facilityYearData.size(); i++) {
            List<FacilityYearData.DataBean.AbnormalRateListBean> abnormalRateList = facilityYearData.get(i).getAbnormalRateList();
            for (int j = 0; j < abnormalRateList.size(); j++) {
                double aDouble = Double.valueOf(abnormalRateList.get(j).getAbnormalRate());
                double aDouble2 = Double.valueOf(abnormalRateList.get(j).getOnlineRate());
                data1[i][j] = new Double(aDouble * 100).intValue();
                data2[i][j] = new Double(aDouble2 * 100).intValue();
            }
        }

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

推荐阅读更多精彩内容