Android Canvas Drawing Column Chart

Source: Internet
Author: User
Tags drawtext

Today, very many applications require some charts. There are also very many third-party charts at the moment. But in their own opinion only if it is not particularly delayed time or choose to use canvas to draw their own more reasonable. Rely on the third-party draw on the demand also Rong easy have a certain discrepancy, and also not easy to expand, so oneself on the basis of the need to draw some statistical chart, the following is the histogram I draw, can be based on a given high and wide from the adaptation, do not know the place can message contact me.

First write a base class, the common module is extracted, which also embodies the design pattern of the abstract factory pattern and template pattern, the following is the base class, some of the common processing code can also be put into the basechartview inside. But because of the time, these will be optimized later.

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;    }    /** returns the maximum value **/     protected Double Getmaxarray (arraylist<double> array) {        if (array.size () = = 0)             return 0;         double max = array.get (0);        for (double i:array) {   &N bsp;        max = max > I?

max:i;        }        return max;    }& nbsp;   /** Returns the minimum value **/    protected double getminarray (arraylist<double> array) { & nbsp      if (array.size () = = 0)             return 0;         double min = array.get (0);        for (double I:arr ay) {            min = Min < I? min:i;       & nbsp;}         return min;    }    protected int px2sp (float Pxvalue) {        final Float scale = context.getresources (). Getdisplaymetrics (). density;        return (int) (Pxvalue/scale + 0.5f);    }   & nbsp;protected int sp2px (float spvalue) {        final Float scale = context.getresources (). Getdisplaymetrics () .density;         return (int) (Spvalue * scale + 0.5f);    }        /**& nbsp;    * from the DP unit according to the resolution of the phone to be px (pixels)      */    protected int dip2px ( Float dpvalue) {        final Float scale = context.getresources (). Getdisplaymetrics () .density;        return (int) (Dpvalue * scale + 0.5f);    }}

The following inherits this base class for drawing:

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> ();p rivate list<string> data_title = new arraylist<string> ();p rivate float margin; Private Paint paint;private Float total_y = 0;private float scale;private float scalewidth;private int width;private int T Extsize;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 * ScaleWidth = width * 9/(Total_y * data_total.size ()-);p aint = new paint ();p Aint.setantialias (true); margin = scal Ewidth;textsize = sp2px (9);} Public Barchartview (context context, AttributeSet Attrs) {Super (context, attrs); width = getresources (). Getdisplaymetrics (). Widthpixels;this.context = Context;paint = new Paint ();p Aint.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); Scalewi DTH = width * 9/(data_total.size) = Scalewidth;textsize = sp2px (9); invalidate ();} public void Drawaxis (canvas canvas) {//Paint.setcolor (Color.yellow);p aint.setstrokewidth (1); Patheffect effects = new Dashpatheffect (new float[] {width/60,width/100, width/50,WIDTH/100}, 1);p aint.setpatheffect (effects);p Aint.setcolor (Color.parsecolor ("#FFD1D1D1")); Canvas.drawline (width /$, Scale * total_y + 0.5f, Width * 31/32,scale * total_y + 0.5f, paint);//Canvas.drawline (+, +, +, paint); NT x = (int) width/20;//paint.settextalign (Paint.Align.CENTER); Fontmetricsint FontMetrics = Paint.getfontmetricsint ();//Reprint Please indicate the Source: Http://blog.csdn.net/hursingpaint.setTextSize ( textSize);p Aint.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,TR UE);//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);p aint.settextalign (Paint.Align.CENTER); float temp = width/20;paint.settextsize (textSize); for (int i = 0; i < data_total.size (); i++) {//Chart.drawself (canvas, PA int);p Aint.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;}} @Overridepublic void OnDraw (canvas canvas) {canvas.drawcolor (color.white);d rawchart (canvas);d rawaxis (canvas);}}
This is good.

Android Canvas Drawing Column Chart

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.