Android canvas绘制柱形统计图

      现在很多应用都需要一些统计图,目前第三方的统计图也有很多,但是在自己看来只要不是特别耽误时间还是选择用canvas自己绘制比较合理,依赖于第三方的绘制在需求上也荣容易有一定出入,而且也不容易扩展,所以自己就根据需求绘制了一些统计图,下面就是我绘制的柱状统计图,可以根据给定高和宽来自适应,不懂的地方可以留言联系我。

   首先写一个基类,将公用的模块提取出来,这也体现设计模式中的抽象工厂模式和模板模式,下面是基类,一些共同处理的代码也可以放到BaseChartView里面,但是由于时间问题,这些会后期进行优化

import java.util.ArrayList;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;


public abstract class BaseChartView extends View {
    protected Context context;
    public ChartView(Context context) {
        super(context);
        this.context= context;
    }

    public ChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context= context;
    }

    public ChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context= context;
    }

    /** 返回最大值 **/
    protected double getMaxArray(ArrayList<Double> array) {
        if (array.size() == 0)
            return 0;
        double max = array.get(0);
        for (double i : array) {
            max = max > i ? max : i;
        }
        return max;
    }

    /** 返回最小值 **/
    protected double getMinArray(ArrayList<Double> array) {
        if (array.size() == 0)
            return 0;
        double min = array.get(0);
        for (double i : array) {
            min = min < i ? min : i;
        }
        return min;
    }

    protected int px2sp(float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    protected int sp2px( float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }
    
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */

    protected int dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

下面就继承这个基类来进行绘图了:

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;

public class BarChartView extends BaseChartView{

	private List<Double> data_total = new ArrayList<Double>();
	private List<String> data_title = new ArrayList<String>();
	private float margin;

	private Paint paint;
	private float total_y = 0;
	private float scale;
	private float scaleWidth;
	private int width;
	private int textSize;

	public BarChartView(Context context, ArrayList<Double> data_total,
			ArrayList<String> data_title) {
		super(context);
		this.context = context;
		width = getResources().getDisplayMetrics().widthPixels;
		this.data_total = data_total;
		this.data_title = data_title;
		total_y = (float) (getMaxArray(data_total) * 1.2);
		scale = width / (3 * total_y);
		scaleWidth = width * 9 / (20 * data_total.size() - 10);
		paint = new Paint();
		paint.setAntiAlias(true);
		margin = scaleWidth;
		textSize = sp2px( 9);
	}

	public BarChartView(Context context, AttributeSet attrs) {
		super(context, attrs);
		width = getResources().getDisplayMetrics().widthPixels;
		this.context = context;
		paint = new Paint();
		paint.setAntiAlias(true);
	}

	public void setData(ArrayList<Double> data_total,
			ArrayList<String> data_title) {
		this.data_total = data_total;
		this.data_title = data_title;
		total_y = (float) (getMaxArray(data_total) * 1.2);
		scale = width / (3 * total_y);
		scaleWidth = width * 9 / (20 * data_total.size() - 10);
		margin = scaleWidth;
		textSize = sp2px(9);
		invalidate();
	}

	public void drawAxis(Canvas canvas) {
		// paint.setColor(Color.YELLOW) ;
		paint.setStrokeWidth(1);
		PathEffect effects = new DashPathEffect(new float[] { width / 60,
				width / 100, width / 50, width / 100 }, 1);
		paint.setPathEffect(effects);
		paint.setColor(Color.parseColor("#FFD1D1D1"));
		canvas.drawLine(width / 36, scale * total_y + 0.5f, width * 31 / 32,
				scale * total_y + 0.5f, paint);
		// canvas.drawLine(30, 20, 30, 300, paint) ;

		int x = (int) width / 20;
		// paint.setTextAlign(Paint.Align.CENTER);
		FontMetricsInt fontMetrics = paint.getFontMetricsInt();
		// 转载请注明出处:http://blog.csdn.net/hursing
		paint.setTextSize(textSize);
		paint.setColor(Color.parseColor("#00000000"));
		for (int i = 0; i < data_title.size(); i++) {
			TextPaint textPaint = new TextPaint();
			textPaint.setTextSize(textSize);
			textPaint.setStrokeWidth(2);
			textPaint.setTextAlign(Paint.Align.CENTER);
			String aboutTheGame = data_title.get(i);
			StaticLayout layout = new StaticLayout(aboutTheGame, textPaint,
					(int) margin * 5 / 4, Alignment.ALIGN_NORMAL, 1.0F, 0.0F,
					true);
			// canvas.translate((int) (x-margin/2),(int) (scale*total_y+5));
			Rect targetRect = new Rect((int) (x - margin / 4), (int) (scale
					* total_y + 5), (int) (x + margin * 5 / 4), (int) (scale
					* total_y * 1.2 + 5));
			canvas.drawRect(targetRect, paint);
			// canvas.drawText(i + 1 + "gg", x, (float) (scale*total_y+20),
			// paint) ;
			int baseline = (targetRect.top - fontMetrics.bottom);
			textPaint.setColor(Color.parseColor("#000000"));
			canvas.translate(targetRect.centerX(), baseline);
			layout.draw(canvas);
			x += margin * 2;
			canvas.translate(-targetRect.centerX(), -baseline);
		}
	}

	public void drawChart(Canvas canvas) {
		// paint.setColor(Color.GREEN) ;

		paint.setTextAlign(Paint.Align.CENTER);
		float temp = width / 20;
		paint.setTextSize(textSize);
		for (int i = 0; i < data_total.size(); i++) {
			// chart.drawSelf(canvas, paint) ;
			paint.setColor(Color.parseColor("#4f91e1"));
			Rect targetRect = new Rect((int) temp,
					(int) (scale * (total_y - data_total.get(i))),
					(int) (temp + margin), (int) (scale * total_y));
			if (data_total.get(i) != 0) {
				canvas.drawRect(targetRect, paint);
			}
			int baseline = targetRect.top - 10;
			paint.setColor(Color.parseColor("#000000"));
			canvas.drawText(data_total.get(i) + "", targetRect.centerX(),
					baseline, paint);
			temp = temp + margin * 2;
		}
	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawColor(Color.WHITE);
		drawChart(canvas);
		drawAxis(canvas);
	}
}
这里就好了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值