Android draw a circular progress bar

Source: Internet
Author: User
Tags drawtext getcolor

First, Background introduction

In our project, we often meet with a circular progress bar, which looks very beautiful and intuitive. Just a few recent projects have this kind of need, record, and by the way review the knowledge of custom view.

Second, the realization of ideas

Customizing view, which is drawing the view in the canvas, requires overriding the OnDraw method. The view can be split into the following sections:

1) need to draw a light green circle

2) need to draw a white circle

3) A display of progress figures in the circle

4) In the circle you can customize the top and bottom different copy tips

III. introduction of the main methods

1, DrawArc: As can be seen, the circle needs to draw an arc to indicate the progress, so choose DrawArc (RECTF Oval, float startangle, float sweepAngle, Boolean usecenter, Paint paint Method

1) Parameters:

Oval-is used to determine the ellipse boundary of an arc shape and dimension (that is, an elliptical bounding rectangle)

startangle-Start Angle (0° at 3 o'clock clock, positive direction counterclockwise)

sweepangle-Rotation Angle (0° at 3 o'clock clock, positive direction counterclockwise)

Whether the usecenter-contains a center point

paint-brushes

2) Drawing principle

    • When RECTF (float left,float top,float right,float bottom) right-left equals bottom-top (long = wide), then a circle is drawn.

    • Centered at the center of the rectangle, 0° at 3 o'clock, counterclockwise in positive direction, startangle degrees from 0°, and ellipse intersecting to get a straight line and a focus.

    • Starting from this line, the Sweepangle degree is rotated in the positive direction, and another line and focus is obtained, so that the arc between the two focus points can be obtained.

2. DrawText (String text, float x, float y, paint paint): How the text is drawn.

Parameters:

text-text

X the distance from the left side of the text to the left of the screen

Y the text baseline the position on the screen

paint-brushes

Note that the parameter y does not represent a position in the vertical direction, but rather the position of the text baseline on the screen.

According to the official API description, the TextAlign property of paint determines the relative position of text relative to the starting coordinate x. By default left, the text is drawn from the right side of X, and if it is center, the x coordinate is in the middle of the text.

Baseline's introduction reference: http://www.xyczero.com/blog/article/20/

Four, draw a circle

1) Draw a background circle

        1-Arc Position: Full circle, then draw progress Arc        Marccirclepaint.setcolor (mcirclebackgroundcolor);        Marccirclepaint.setstrokewidth (mstrokewidth);        Screen width        int width = getmeasuredwidth ();        RECTF RECTF = new RECTF ();        Rectf.left = (width-mwidth)/2;//upper left corner x        rectf.top = mwidth*0.1f;//upper left corner y        rectf.right = (width-mwidth)/2+mwidth;// upper right corner x        rectf.bottom = mwidth*0.9f;//upper right corner y        if ((Rectf.right-rectf.left) > (rectf.bottom-rectf.top)) {//Square rectangle Ensures that the drawn circle does not turn into an oval            float space = (rectf.right-rectf.left)-(rectf.bottom-rectf.top);            Rectf.left + = SPACE/2;            Rectf.right-= SPACE/2;        }        Canvas.drawarc (rectf,270,360,false,marccirclepaint);//2nd parameter: Clock at 3 points 0 degrees, counterclockwise positive direction

2) Draw Progress Circle

Use the same paint, change its color, draw a circle of the same size on the canvas, but the rotation angle value is not the same.

Marccirclepaint.setcolor (Mprogresscolor); Set the corner to round Marccirclepaint.setstrokecap (Paint.Cap.ROUND); Marccirclepaint.setstrokewidth (Minnerstrokewidth); Canvas.drawarc (Rectf,270,manglevalue,false,marccirclepaint);

3) Draw Text

Different text is not the same position, the calculation of a good position can be drawn out text.

        2-The position of the text: center display int centerx = WIDTH/2;        Computes the text width int textWidth = (int) mtextpaint.measuretext (mText, 0, Mtext.length ());        Calculated baseline: Centered vertically paint.fontmetricsint FontMetrics = Mtextpaint.getfontmetricsint ();        int baseline = (Getmeasuredheight ()-Fontmetrics.bottom + fontmetrics.top)/2-fontmetrics.top;        int textx = CENTERX-TEXTWIDTH/2;        Mtextpaint.setcolor (Mtextcolor);        Mtextpaint.settextsize (mtextsize);        Canvas.drawtext (Mtext,textx,baseline,mtextpaint); if (mtoptext! = null &&!mtoptext.equals ("")) {textWidth = (int) mtextpaint.measuretext (mtoptext, 0, M            Toptext.length ());            TEXTX = CENTERX-TEXTWIDTH/2;            Mtextpaint.settextsize (mtoptextsize);            Mtextpaint.setcolor (Mtoptextcolor);        Canvas.drawtext (Mtoptext, TEXTX, baseline-20, Mtextpaint); } if (Mbottomtext! = null &&!mbottomtext.equals ("")) {textWidth = (int) Mtextpaint.measuretext (mbottomtext, 0, Mbottomtext.length ());            TEXTX = centerx-textwidth/2;//mtextpaint.reset ();//Mtextpaint.setantialias (TRUE);//            Mtextpaint.setlineartext (TRUE);            Mtextpaint.settextsize (mtoptextsize);            Mtextpaint.setcolor (Mbottomtextcolor);        Canvas.drawtext (Mbottomtext, TEXTX, Baseline +, mtextpaint); }

V. Summary

In fact, a lot of custom view is drawn in canvas canvases, looking at the complex (in fact, difficult to calculate the location), but as long as it is split into several points, one by one to draw a combination of the good.

Attach Source code: Project Demo

Package Com.example.viewdemo;import Android.content.context;import Android.graphics.*;import Android.util.attributeset;import android.view.view;/** * Custom view mode Three: Redraw, inherit view * First step: Draw out the Circle DrawArc * Step two: Draw the progress Circle DrawArc * Step three: Draw text: Middle text, top text, bottom text DrawText * Created by Cjy on 17/6/14.    */public class Arccircleview extends View {private Context mcontext;    /** * Text Brush */private Paint mtextpaint;    /** * ARC Brush */Private Paint marccirclepaint;    /** * Width * */private float mwidth = 100.0f;    /** * Text * */private String MText = "0%";    /** * Bottom Text */private String Mtoptext = "";    /** * Bottom Text */private String Mbottomtext = "";    /** * radians * */private int manglevalue = 0;    /** * Round background color: Default light green */private int mcirclebackgroundcolor = 0x4c11af9c;    /** * Progress Color, default white */private int mprogresscolor = 0xFFFFFFFF;    /** * The color of the top text, default white */private int mtoptextcolor = 0xFFFFFFFF; /** * The color of the bottom text, default white */private int mbottomtextcolor = 0xFFFFFFFF;    /** * Text color, default white */private int mtextcolor = 0xFFFFFFFF;    /** * Edge Width */private int mstrokewidth = 8;    /** * Progress Round edge width */private int minnerstrokewidth = 7;    /** * Text Size */private int mtextsize = 12;    /** * Top Text Size */private int mtoptextsize = 10;        Public Arccircleview (Context context) {super (context);    Init (context);        } public Arccircleview (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context);        } public Arccircleview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);    Init (context);        } private void Init (context context) {Mcontext = context;        Mtextpaint = new Paint ();        Set anti-aliasing Mtextpaint.setantialias (true);        Make the text appear clearer mtextpaint.setlineartext (true);        Marccirclepaint = new Paint (); Marccirclepaint.setAntiAlias (TRUE);    Marccirclepaint.setstyle (Paint.Style.STROKE);        } public void SetWidth (float width) {mwidth = width;    Invalidate ();        The public void SetText (String text) {mText = text;    Invalidate ();        The public void Settoptext (String text) {mtoptext = text;    Invalidate ();        The public void Setbottomtext (String text) {mbottomtext = text;    Invalidate ();        The public void SetTextColor (int textcolor) {this.mtextcolor = Mcontext.getresources (). GetColor (TextColor);    Invalidate (); The public void Setbottomtextcolor (int bottomtextcolor) {this.mbottomtextcolor = Mcontext.getresources (). GetColor        (Bottomtextcolor);    Invalidate (); The public void Settoptextcolor (int toptextcolor) {this.mtoptextcolor = Mcontext.getresources (). GetColor (TOPTEXTC        Olor);    Invalidate (); } public void Setprogresscolor (int progresscolor) {this.mprogresscolor = Mcontext.getresources (). GetColor (Progresscolor);    Invalidate (); } public void Setcirclebackgroundcolor (int circlebackgroundcolor) {This.mcirclebackgroundcolor = Mcontext.getre        Sources (). GetColor (Circlebackgroundcolor);    Invalidate ();        } public void Setstrokewidth (int strokewidth) {this.mstrokewidth = Strokewidth;    Invalidate ();        } public void Setinnerstrokewidth (int innerstrokewidth) {this.minnerstrokewidth = Innerstrokewidth;    Invalidate ();        } public void settextsize (int textSize) {this.mtextsize = textSize;    Invalidate ();        } public void settoptextsize (int toptextsize) {this.mtoptextsize = toptextsize;    Invalidate ();  }/** * Set progress * @param progress */public void setprogress (float progress) {int anglevalue = (int)        ((Progress * 1.0)/100 * 360);            if (Anglevalue! = 0 && Progress <=) {manglevalue = Anglevalue;   MText = string.valueof (progress) + "%";     } invalidate ();        } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        1-Arc Position: Full circle, then draw progress Arc Marccirclepaint.setcolor (Mcirclebackgroundcolor);        Marccirclepaint.setstrokewidth (Mstrokewidth);        Screen width int width = getmeasuredwidth ();        RECTF RECTF = new RECTF (); Rectf.left = (width-mwidth)/2;//upper left corner x rectf.top = mwidth*0.1f;//upper left corner y rectf.right = (width-mwidth)/2+mwidth;// upper right corner x Rectf.bottom = mwidth*0.9f;//upper right corner y if ((rectf.right-rectf.left) > (rectf.bottom-rectf.top)) {//Square moment            Shape to ensure that the drawn circle does not become oval float space = (rectf.right-rectf.left)-(rectf.bottom-rectf.top);            Rectf.left + = SPACE/2;        Rectf.right-= SPACE/2; } canvas.drawarc (Rectf,270,360,false,marccirclepaint),///2nd parameter: Clock at 3 points is 0 degrees, counterclockwise is positive direction marccirclepaint.setcolor (Mpro        Gresscolor);        Set the corner to round Marccirclepaint.setstrokecap (Paint.Cap.ROUND); Marccirclepaint.setstroKewidth (Minnerstrokewidth);        Canvas.drawarc (Rectf,270,manglevalue,false,marccirclepaint);        2-The position of the text: center display int centerx = WIDTH/2;        Computes the text width int textWidth = (int) mtextpaint.measuretext (mText, 0, Mtext.length ());        Calculated baseline: Centered vertically paint.fontmetricsint FontMetrics = Mtextpaint.getfontmetricsint ();        int baseline = (Getmeasuredheight ()-Fontmetrics.bottom + fontmetrics.top)/2-fontmetrics.top;        int textx = CENTERX-TEXTWIDTH/2;        Mtextpaint.setcolor (Mtextcolor);        Mtextpaint.settextsize (mtextsize);        Canvas.drawtext (Mtext,textx,baseline,mtextpaint); if (mtoptext! = null &&!mtoptext.equals ("")) {textWidth = (int) mtextpaint.measuretext (mtoptext, 0, M            Toptext.length ());            TEXTX = CENTERX-TEXTWIDTH/2;            Mtextpaint.settextsize (mtoptextsize);            Mtextpaint.setcolor (Mtoptextcolor);        Canvas.drawtext (Mtoptext, TEXTX, baseline-20, Mtextpaint);   }     if (mbottomtext! = null &&!mbottomtext.equals ("")) {textWidth = (int) mtextpaint.measuretext (mBo            Ttomtext, 0, Mbottomtext.length ());            TEXTX = centerx-textwidth/2;//mtextpaint.reset ();//Mtextpaint.setantialias (TRUE);//            Mtextpaint.setlineartext (TRUE);            Mtextpaint.settextsize (mtoptextsize);            Mtextpaint.setcolor (Mbottomtextcolor);        Canvas.drawtext (Mbottomtext, TEXTX, Baseline +, mtextpaint); }    }}

  

Android draw a circular progress bar

Related Article

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.