Android柱状图的实现

来来来,先看个效果
Android柱状图的实现_第1张图片
X轴的字体大小是可以调整的

//传入的数据
/**
 * 传进来的数组要求保持数组长度一致
*/
public void setBarGraphData(@NonNull int[][] barGraphDataList, int[] barGraphColorList, String[] barGraphTextList) {
        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();
    }

git项目地址:https://github.com/ytttp/BarGraphDemo 注释写得应该挺清楚的

可以直接引用

dependencies {
    ... ...
    compile 'com.ytt.bargraph:bargraphlibrary:1.0'
}

当然要保证project/build.gradle下面是

allprojects {
    repositories {
        jcenter()
    }
}

在xml中引用


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">


    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#DEDEDE"
        android:scrollbars="none">

        <com.ytt.bargraph.bargraphlibrary.BarGraphView
            android:id="@+id/bargraphview"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            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" />
    HorizontalScrollView>
LinearLayout>

简单设置数据

BarGraphView bargraphview = (BarGraphView) findViewById(R.id.bargraphview);
int[][] data = {{182, 89, 78, 88}, {34, 85, 16, 96}, {46, 29, 78, 41}, {54, 75, 54, 12}};
int[] colorData = {Color.RED, Color.BLACK, Color.GRAY, Color.GREEN, Color.LTGRAY};
String[] textData = {"一月份", "二月份", "三月份", "四月份"};
bargraphview.setBarGraphData(data, colorData, textData);

你可能感兴趣的:(android)