Android-Line chart

Source: Internet
Author: User

Using the Android canvas, draw a line chart: The code is:

Package Spt.view;import Android.annotation.suppresslint;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.dashpatheffect;import Android.graphics.paint;import Android.graphics.path;import Android.graphics.patheffect;import Android.util.Log; Import android.view.view;/** * In order to extend the compatibility of phones with different resolutions, percentages and some important variables are set to final, and other mutable variables are set to member variables. * * * @author Administrator * * */@SuppressLint ("Drawallocation") public class Brokenlineview extends View {//Calculate relative proportions, use margin m The argin is in accordance with (the value is inversely proportional to the proportion result).//The proportion of arrows when drawing axes. private static final int arrow_pecent = 10;//x, y axis coordinate point text. private static final int x_t Ext_pecent = 10;private static final int y_text_pecent = 10;//The proportions of the caption text. private static final int title_text_pecent = 5;//default The value of the axis. private static final string[] x_lable = {"A", "B", "C", "D", "E", "F", "G"};p rivate static final string[] Y_lable = {"0", "50", "100", "150", "200", "250", "300"};//the radius of the data point circle. private static final int dataradius = 10;//x, y axis coordinate point number position deviation from axis Distance. Private int xtextdistanceaxis = 20;private int ytextdistanceaxis = 30;//The value of the numeric text of the data point relative to the height of the data point. private int Datatextabovecircle  = 25;//margin (also cannot be final, because it may be possible for users to set different spacing depending on the conditions. private int margin = 100;//x, y axis unit length private int xscale = 20;private int Yscale = 20;//the height of the caption. Private String title;//the y distance from the topmost line. private int titleheight = 20;//origin coordinate private int x0point;private int y0 point;//display text above x, Y axis private string[] Xlabel = null;private string[] Ylabel = null;//curve Data private int[] data = Null;public Brokenlineview (context context, String title, string[] xlabel,string[] ylabel, int[] data) {super (context); this.title = t itle;//If a null value is passed, the default value is used. This.xlabel = (Xlabel = = null? X_lable:xlabel); This.ylabel = (Ylabel = = null?) Y_lable:ylabel); if (data = null) throw new RuntimeException ("Data cannot null:"); this.data = data;} Public Brokenlineview (Context context) {This (context, NULL, x_lable, y_lable, null);} Sets the coordinate origin position and the unit length on the axis. public void init () {x0point = margin;//x0.y0point = getheight ()-margin;//y0. XScale = (getwidth ()-2 * margin)/(this.xlabel.length-1); Yscale = (GetHeight ()-2 * margin)/(This.yLabel.length- 1);} public int GetMargin () {return margin;} public void setmargin (int margin) {if (margin < 0) throw new RuntimeException ("Gap cannot be negative:" + margin); this.margin = margin; } @Overrideprotected void OnDraw (canvas canvas) {canvas.drawcolor (color.black);//Background color. Paint p = new paint ();p. SetStyle (Paint.Style.STROKE); Sets the style of the outer frame of the Axis "hollow" (STROKE). P.setantialias (True); Anti-aliasing P.setcolor (color.white);p. Setstrokewidth (2); Sets the width of the outer frame of the axis. Init ();d rawyaxis (Canvas, p);d rawxaxis (Canvas, p);d rawhorizontalline (canvas);d rawdata (canvas); X-to-line private void drawhorizontalline (canvas canvas) {Paint paint = new Paint ();p Aint.setstyle (Paint.Style.STROKE); Paint.setcolor (Color.gray); Path PATH = new path ();//Draw a solid line with a length of 1, then a blank length of 10, then draw a length of 1 solid line, and then draw a blank length of 10; the last one is an offset, which can be ignored. Patheffect effects = new Dashpatheffect (new float[] {1, ten, 1, 1, 1);p aint.setpatheffect (effects); for (int i =; (Y0point-i * Yscale) >= margin; i++) {int StartX = X0point;int Starty = y0point-i * Yscale;int stopx = x0point + (xlabel.length-1) * Xscale;path.movet O (StartX, starty);p Ath.lineto (stopx, Starty);p Aint.setcolor (Color.dkgray); Canvas.drawpath (path, paint);}} /** * Draw Y-Axis * * @param canvas * @param p */private void Drawyaxis (canvas canvas, Paint p) {//Y-axis. Canvas.drawline (X0point, Y0point, margin, margin, p);//The left part of the y-axis arrow. Canvas.drawline (X0point, margin, x0point-x0point/arrow_pecent,margin + margin /arrow_pecent, p);//The right part of the y-axis arrow. Canvas.drawline (X0point, margin, X0point + x0point/arrow_pecent,margin + margin/arrow_p Ecent, p);} /** * Draw x axis. * * @param canvas * @param p */private void Drawxaxis (canvas canvas, Paint p) {//X-axis. Canvas.drawline (x0point, Y0point, ge Twidth ()-Margin, y0point, p);//The upper part of the x-axis arrow. Canvas.drawline (getwidth ()-Margin, Y0point, getwidth ()-Margin-margin/arr Ow_pecent, Y0point-margin/arrow_pecent, p);//The lower part of the x-axis arrow. Canvas.drawline (getwidth ()-Margin, Y0point, getwidth ()-Marg Inch-Margin/arrow_pecent, Y0point + margin/arrow_pecent, p);} Draw Data private void drawdata (canvas canvas) {Paint p = new Paint ();p. Setantialias (TRUE);//antialiasing. P.setcolor (color.red);p. SE Ttextsize (margin/x_text_pecent); for (int X = 0; x < data.length; + +) {int StartX = x0point + x * xscale;//axis coordinate point text display . Canvas.drawtext (Xlabel[x], StartX, Y0point + Xtextdistanceaxis, p);//number of points of the circle. Canvas.drawcircle (StartX, Caly (data[x)), Dataradius, p);//The data value on the data point. Canvas.drawtext (Data[x] + "", StartX, Caly (data[x]) + dataradius-datatextabovecircle, p);// Draw a change line between the data point circles.//Draw a line, the last data point does not perform an operation. if (x! = data.length-1) canvas.drawline (StartX, Caly (data[x)), StartX + xscale,caly (data[x + 1]), p);} For x.//draws the y-axis coordinate point text. Paint py = new paint ();p Y.setantialias (true); antialiasing. Py.setcolor (color.red);p y.settextsize (margin/y_text_pecent); for (int Y = 0; y < ylabel.length; y++) {int start y = y0point-y * yscale;//y-Axis coordinate point text display. Canvas.drawtext (Ylabel[y], X0point-ytextdistanceaxis, starty, py);} For y.//to draw a caption. Paint PTitle = new Paint ();p Title.setantialias (true); Anti-aliasing. Ptitle.setcolor (color.red);p title.settextsize (margin/title_text_pecent);//The pixels of the title length are calculated by Paint.measuretext, The title is then centered horizontally. Canvas.drawtext (title, (GetWidth ()-Ptitle.measuretext (title))/2,margin-titleheight, ptitle);} /** * Calculates the position of the data value in the coordinate system Y. * * @param y * @return */private int caly (int y) {int y0 = 0;int Y1 = 0;try {y0 = Integer.parseint (ylabel[0]); y1 = Intege R.parseint (ylabel[1]); return Y0point-((y-y0) * Yscale/(Y1-Y0));} catch (NumberFormatException e) {log.d ("Sysout", "Y-axis label must be number:" + e.getmessage ()); return-1;}}

You can then invoke it in the activity:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//test:int[] data = {  0, 121, Wu,};final String title = "Recent Weekly AQI Change chart"; Setcontentview (new Brokenlineview (this, title, NULL, NULL, data)); Initview ();}

Android-Line 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.