Android canvas绘制柱形统计图

Posted jzdwajue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android canvas绘制柱形统计图相关的知识,希望对你有一定的参考价值。

      如今非常多应用都须要一些统计图。眼下第三方的统计图也有非常多。可是在自己看来仅仅要不是特别耽误时间还是选择用canvas自己绘制比較合理。依赖于第三方的绘制在需求上也荣easy有一定出入,并且也不easy扩展,所以自己就依据需求绘制了一些统计图,以下就是我绘制的柱状统计图,能够依据给定高和宽来自适应,不懂的地方能够留言联系我。

   首先写一个基类,将公用的模块提取出来,这也体现设计模式中的抽象工厂模式和模板模式,以下是基类,一些共同处理的代码也能够放到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);
	}
}
这里就好了



以上是关于Android canvas绘制柱形统计图的主要内容,如果未能解决你的问题,请参考以下文章

WPF 实现柱形统计图

canvas 画布 绘制柱形图

Android柱形图 绘制

ECharts.js学习 简单入门

canvas动态绘制饼状图,

android中,如何用canvas绘制透明?