自定义控件之柱状图

新的项目需求中有柱状图(如图)

黄色区域为字体

下面附上代码

,代码中我都注释上中文,你们可以按照自己需求自己改动

 

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.sysom.douthree.R;
import com.sysom.douthree.Utils.ScreenUtils;
import com.sysom.douthree.Utils.Utility;

/**
 * 自定义组件:柱状图
 * Created by hanj on 14-12-30.
 */
public class BarChartViewone extends View {
    private int screenW, screenH;

    private BarChartItemBean[] mItems;
    //max value in mItems.
    private float maxValue;
    //max height of the bar
    private int maxHeight;
    private int[] mBarColors = new int[]{};
    private Paint barPaint, linePaint, textPaint;
    private Rect barRect, leftWhiteRect, rightWhiteRect;
    private Path textPath;

    private int leftMargin, topMargin, smallMargin;
    //the width of one bar item
    private int barItemWidth;
    //the spacing between two bar items.
    private int barSpace;
    //the width of the line.
    private int lineStrokeWidth;

    /**
     * The x-position of y-index and the y-position of the x-index..
     */
    private float x_index_startY, y_index_startX;

    private Bitmap arrowBmp;
    private Paint ciText;//Y轴字
    private Rect x_index_arrowRect, y_index_arrowRect;

    private static final int BG_COLOR = Color.parseColor("#E5E5E5");
    private static final int F2 = Color.parseColor("#F2F2F2");
    private static final int AF = Color.parseColor("#B0AFAF");

    private Bitmap background;
    // private static final int BG_COLOR1 = Color.parseColor("#FFFFFF");


    public BarChartViewone(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    private void init(Context context) {
        screenW = ScreenUtils.getScreenW(context);
        screenH = ScreenUtils.getScreenH(context);

        leftMargin = ScreenUtils.dp2px(context, 26);
        topMargin = ScreenUtils.dp2px(context,40);
        smallMargin = ScreenUtils.dp2px(context, 6);

        barPaint = new Paint();

        //barPaint.setShader(shader/*mBarColors[0]*/);

        linePaint = new Paint();
        //划线宽度
        lineStrokeWidth = ScreenUtils.dp2px(context, 1);

        linePaint.setStrokeWidth(lineStrokeWidth);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(AF);

        barRect = new Rect(0, 0, 0, 0);
        textPath = new Path();

        leftWhiteRect = new Rect(0, 0, 0, screenH);
        rightWhiteRect = new Rect(screenW - leftMargin, 0, screenW, screenH);

     //   arrowBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_up);

        //为柱状图设置背景图图片
        background = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg_zhuzhuangtu);


        ciText = new Paint();   //设置Y轴单位画笔  Y轴箭头改字
        ciText.setColor(F2);
        ciText.setTextSize(18);
    }

    //标记是否已经获取过状态拉的高度
    private boolean statusHeightHasGet;


    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zhuazhuangtu_zuigao);
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (!statusHeightHasGet) {
            subStatusBarHeight();
            statusHeightHasGet = true;
        }

        //draw background
     //   canvas.drawColor(BG_COLOR);

        //bounds禁止滑动
        checkLeftMoving();

        textPaint.setTextSize(ScreenUtils.dp2px(getContext(), 12));
        for (int i = 0; i < mItems.length; i++) {
            //draw bar rect
            barRect.left = (int) y_index_startX + barItemWidth * i + barSpace * (i + 1) /*- (int) leftMoving*/;///*- (int) leftMoving*拖动效果初始值-248/
       //     Log.e("aa", "left: "+barRect.left +"\ny_index_startX:"+y_index_startX+"\ni:"+i+"\nbarspace:"+barSpace+"\nleftMoving:"+leftMoving);
            barRect.top = topMargin * 2 + (int) (maxHeight * (1.0f - mItems[i].itemValue / maxValue));
            barRect.right = barRect.left + barItemWidth;

        //    barPaint.setColor(mBarColors[i % mBarColors.length]);
//            canvas.drawRect(barRect, barPaint);
            // FIXME: 2017/5/27 改柱状图背景图片
         //   Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zhuazhuangtu_zuigao);
           //防止bitmap创建多次(ondraw会走多次)
            canvas.drawBitmap(bitmap,null,barRect,null);

             //bitmap.recycle();
            //draw type text
            String typeText = mItems[i].itemType;
            float textPathStartX = barRect.left + barItemWidth / 2 - 30;
                 /*   -(float) (Math.sin(Math.PI / 6)) * textPaint.measureText("10-11")/2;//這裡改下面数字的左右距离,是否对中*/



            float textPathStartY = barRect.bottom+20;
            textPath.reset();
            textPath.moveTo(textPathStartX, textPathStartY);
            textPath.lineTo(textPathStartX + (float) (1000 * Math.tan(Math.PI / 6)), textPathStartY );
            textPaint.setTextSize(18);//设置X轴下面字体大小
            canvas.drawTextOnPath(typeText, textPath, smallMargin * 1.5f, smallMargin * 2, textPaint);

            //draw value text
            String valueText = String.valueOf(mItems[i].itemValue);
            textPaint.setColor(AF);
            textPaint.setTextSize(26);//设置上面字体代大小
            canvas.drawText(valueText, barRect.left - (textPaint.measureText(valueText) - barItemWidth) / 2,
                    barRect.top - smallMargin, textPaint);
        }

        //draw left white space and right white space
        int c = barPaint.getColor();
        //右侧一小条背景颜色
        //barPaint.setColor();
        leftWhiteRect.right = (int) y_index_startX;

        canvas.drawRect(leftWhiteRect, barPaint);
        canvas.drawRect(rightWhiteRect, barPaint);
        barPaint.setColor(c);

        //draw x-index line.
        linePaint.setARGB(255,85,187,215);

        canvas.drawLine(
                y_index_startX - lineStrokeWidth / 2+10,
                x_index_startY,
                screenW - leftMargin+10,
                x_index_startY,
                linePaint);

        //draw y-index line.
        canvas.drawLine(
                y_index_startX+10,    //+10  Y轴往内偏
                x_index_startY + lineStrokeWidth / 2,
                y_index_startX+10,
                topMargin / 2 -1 ,  //Y轴长度+ 表示负方向
                linePaint);

        linePaint.setARGB(255,85,187,215);

       // canvas.drawBitmap(arrowBmp, null, y_index_arrowRect, null);
        //参数二相对X轴距离    参数三相对Y轴距离
        canvas.drawText("km",2,y_index_arrowRect.top+12,ciText);//改Y轴单位   箭头改次字
        canvas.save();
        //canvas.rotate(90, (x_index_arrowRect.left + x_index_arrowRect.right) / 2, (x_index_arrowRect.top + x_index_arrowRect.bottom) / 2);
        //canvas.drawBitmap(arrowBmp, null, x_index_arrowRect, null);
      //  canvas.restore();

        //draw division value

       // int maxDivisionValueHeight = (int) (maxHeight * 1.0f / maxValue * maxDivisionValue)+20;//Y轴刻度
     //   textPaint.setTextSize(ScreenUtils.dp2px(getContext(),26));
       /* for (int i = 0; i <= 1; i++) {
            float startY = barRect.bottom - *//*maxDivisionValueHeight * 0.1f*//*barRect.bottom * i;
            if (startY < topMargin / 2) {
                break;
            }*/
            //X轴负方向小横线
            canvas.drawLine(y_index_startX+10, barRect.bottom*0.2f, y_index_startX + 20, barRect.bottom*0.2f, linePaint);

          /*  String text = String.valueOf(maxDivisionValue * 0.1f * i);
            canvas.drawText(text,
                    y_index_startX - textPaint.measureText(text) - 5,
                    startY + textPaint.measureText("0") / 2,
                    textPaint);
        }*/
    }

    private float leftMoving;
    private float lastPointX;
    private float movingLeftThisTime = 0.0f;

    @Override
    public boolean onTouchEvent( MotionEvent event) {
        int type = event.getAction();

        switch (type) {
            case MotionEvent.ACTION_DOWN:
                lastPointX = event.getRawX();
                break;

            case MotionEvent.ACTION_MOVE:
                float x = event.getRawX();
                movingLeftThisTime = lastPointX - x;

                leftMoving += movingLeftThisTime;
                lastPointX = x;

                invalidate();
                break;

            case MotionEvent.ACTION_UP:
                //smooth scroll
                new Thread(new SmoothScrollThread(movingLeftThisTime)).start();
                break;

            default:
                return super.onTouchEvent(event);
        }

        return true;
    }

    /**
     * Check the value of leftMoving to ensure that the view is not out of the screen.
     */
    private void checkLeftMoving() {
        if (leftMoving < 0) {
            leftMoving = 0;
        }

        if (leftMoving > (maxRight - minRight)) {
            leftMoving = maxRight - minRight;
        }
    }

    public BarChartItemBean[] getItems() {
        return mItems;
    }


    public void setItems(BarChartItemBean[] itemone) {
        if (itemone == null) {
            throw new RuntimeException("BarChartView.setItems(): the param items cannot be null.");
        }
        if (itemone.length == 0) {
            return;
        }

        this.mItems = itemone;

        //Calculate the max value.
        maxValue = itemone[0].itemValue;
        for (BarChartItemBean bean : itemone) {
            if (bean.itemValue > maxValue) {
                maxValue = bean.itemValue;
            }
        }

        //Calculate the max division value.
        getRange(maxValue, 0);

        //Get the width of each bar.
        getBarItemWidth(screenW, itemone.length);

        //Refresh the view.
        invalidate();
    }

    private int maxRight, minRight;

    /**
     * Get the width of each bar which is depended on the screenW and item count.
     */
    private void getBarItemWidth(int screenW, int itemCount) {
        //The min width of the bar is 50dp.
        int minBarWidth = ScreenUtils.dp2px(getContext(), 20);
        //The min width of spacing.
        int minBarSpacing = ScreenUtils.dp2px(getContext(),20);

      //  barItemWidth = (screenW - leftMargin * 2) / (itemCount + 3);
     //   barItemWidth = minBarWidth;   //均分X轴

        barItemWidth = ScreenUtils.px2dp(getContext(),18);   //设置柱子的图形宽度18
        barSpace = (screenW /*- leftMargin * 2*/ - barItemWidth * itemCount) / (itemCount + 1)-20;//可更改柱子之间的间距

       /* if (barItemWidth < minBarWidth || barSpace < minBarSpacing) {

            //barSpace = minBarSpacing;
        }*/

        maxRight = (int) y_index_startX + lineStrokeWidth + (barSpace + barItemWidth) * mItems.length;
        minRight = screenW - leftMargin - barSpace;
    }

    /**
     * Sub the height of status bar and action bar to get the accurate height of screen.
     */
    private void subStatusBarHeight() {
        //The height of the status bar
        int statusHeight = ScreenUtils.getStatusBarHeight((Activity) getContext());
        //The height of the actionBar
 //注释       ActionBar ab = ((ActionBarActivity) getContext()).getSupportActionBar();
    //注释    int abHeight = ab == null ? 0 : ab.getHeight();

      //注释  screenH -= (statusHeight + abHeight);

        barRect.top = topMargin * 2;
        barRect.bottom = screenH - topMargin * 3;
        maxHeight = barRect.bottom - barRect.top;

        x_index_startY = barRect.bottom;
        x_index_arrowRect = new Rect(screenW - leftMargin, (int) (x_index_startY - 10),
                screenW - leftMargin + 10, (int) (x_index_startY + 10));
    }

    //The max and min division value.
    private float maxDivisionValue, minDivisionValue;

    //Get the max and min division value by the max and min value in mItems.
    private void getRange(float maxValue, float minValue) {
        //max
        int scale = Utility.getScale(maxValue);
        float unscaledValue = (float) (maxValue / Math.pow(10, scale));

//<--Y轴刻度及标识-->
     //   maxDivisionValue = (float) (getRangeTop(unscaledValue) * Math.pow(10, scale));

       // y_index_startX = getDivisionTextMaxWidth(maxDivisionValue) + 10;
      y_index_arrowRect = new Rect((int) (y_index_startX - 5), topMargin / 2 - 20,
             (int) (y_index_startX + 5), topMargin / 2);

    }

  /*  private float getRangeTop(float value) {
        //value: [1,10)
        if (value < 1.2) {
            return 1.2f;
        }

        if (value < 1.5) {
            return 1.5f;
        }

        if (value < 2.0) {
            return 2.0f;
        }

        if (value < 3.0) {
            return 30f;
        }

        if (value < 4.0) {
            return 4.0f;
        }

        if (value < 5.0) {
            return 5.0f;
        }

        if (value < 6.0) {
            return 6.0f;
        }

        if (value < 8.0) {
            return 8.0f;
        }

        return 10.0f;
    }*/

    /**
     * Get the max width of the division value text.
     */
    private float getDivisionTextMaxWidth(float maxDivisionValue) {
        Paint textPaint = new Paint();
        textPaint.setTextSize(ScreenUtils.dp2px(getContext(), 10));

        float max = textPaint.measureText(String.valueOf(maxDivisionValue * 0.1f));
        for (int i = 2; i <= 10; i++) {
            float w = textPaint.measureText(String.valueOf(maxDivisionValue * 0.1f * i));
            if (w > max) {
                max = w;
            }
        }

        return max;
    }

    /**
     * Use this thread to create a smooth scroll after ACTION_UP.
     */
    private class SmoothScrollThread implements Runnable {
        float lastMoving;
        boolean scrolling = true;

        private SmoothScrollThread(float lastMoving) {
            this.lastMoving = lastMoving;
            scrolling = true;
        }

        @Override
        public void run() {
            while (scrolling) {
                long start = System.currentTimeMillis();
                lastMoving = (int) (0.9f * lastMoving);
                leftMoving += lastMoving;

                checkLeftMoving();
                postInvalidate();

                if (Math.abs(lastMoving) < 5) {
                    scrolling = false;
                }

                long end = System.currentTimeMillis();
                if (end - start < 20) {
                    try {
                        Thread.sleep(20 - (end - start));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * A model class to keep the bar item info.
     */
    public static class BarChartItemBean {
        private String itemType;
        private float itemValue;

        public BarChartItemBean(String itemType, float itemValue) {
            this.itemType = itemType;
            this.itemValue = itemValue;
        }
    }
}

 

在我们需要的视图中把自定义控件New出来然后传入itemType(X轴下方数据) / itemValue(条形上方数据)

总布局就不贴了

 

数据显示工具类

 

import java.text.DecimalFormat;

/**
 * 工具类
 * Created by hanj on 14-12-30.
 */
public class Utility {
    /**
     * 格式化浮点数据,保留1位小数
     */
    public static String formatFloat(double value) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(value);
    }

    public static int getScale(float value) {
        if (value >= 1 && value < 10) {
            return 0;
        }

        if (value >= 10) {
            return 1 + getScale(value / 10);
        } else {
            return getScale(value * 10) - 1;
        }
    }

 

 

屏幕适配工具类

 

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;

/**
 * ScreenUtils
 * Created by hanj on 14-9-25.
 */
public class ScreenUtils {
    private static int screenW;
    private static int screenH;
    private static float screenDensity;

    public static int getScreenW(Context context) {
        if (screenW == 0) {
            initScreen(context);
        }
        return screenW;
    }

    public static int getScreenH(Context context) {
        if (screenH == 0) {
            initScreen(context);
        }
        return screenH;
    }

    public static float getScreenDensity(Context context) {
        if (screenDensity == 0) {
            initScreen(context);
        }
        return screenDensity;
    }

    private static void initScreen(Context context) {
        DisplayMetrics metric = context.getResources().getDisplayMetrics();
        screenW =760;
        screenH = 270;
      /*  screenW = metric.widthPixels;
        screenH = metric.heightPixels;*///全屏适配
        screenDensity = metric.density;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        return (int) (dpValue * getScreenDensity(context) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        return (int) (pxValue / getScreenDensity(context) + 0.5f);
    }

    /**
     * 计算状态栏高度
     */
    public static int getStatusBarHeight(Activity ac) {
        Rect frame = new Rect();
        ac.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }
}

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值