Android custom control implements a circular progress bar with text and numbers

Source: Internet
Author: User
Tags drawtext getcolor

The implementation is as follows:


The first step: Draw a hollow circle below the gap, called the outer big arc Bar

Anvas . ClipRect (00    mwidth       4 ) ; 
The second step: calculate the starting angle when drawing the arc progress bar, set as the left end of the outer large arc for the progress is worth starting point, sweep the angle of the external large arc of the percentage is the progress value

Step three: Draw numbers, text, percent signs

Fourth step: Use handler Runnable and Decelerateinterpolator are progress bars and numbers moving up

Test code:

FinalCustomcirclebarCircle=(Customcirclebar) Findviewbyid (r.id.Win_home);Circle.Setpercent (Ten);Circle.Setcustomtext (" very well");Circle.Setprogesscolor (Getresources ().GetColor (R.color.Blue));FinalRandomRandom=NewRandom ();Circle.Setonclicklistener (NewView.onclicklistener(){@Override    Public voidOnClick (Viewv){Circle.Setpercent (Random.Nextint ( -)); }});
The completion code is as follows:

public class Customcirclebar extends View {private context context;    /* Progress value */private int percent;    /* Color value */private int mprogesscolor;    /* The text name below */private String mcustomtext;    /* Brush for Outer ring ring */private paint Paintbar = new paint ();    /* Brush for text below */private paint Painttext = new paint ();    /* Dynamically Get property values */private typedvalue typedvalue;    /* speed up and then slow down * * decelerateinterpolator mdecelerateinterpolator = new Decelerateinterpolator ();    /* Animation duration */private int duration = 10;    private int curtime = 0;        Public Customcirclebar (Context context) {super (context);        This.context=context;    Init ();        } public Customcirclebar (context context, AttributeSet Attrs) {Super (context, attrs);        This.context=context;    Init (); } public Customcirclebar (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyle        ATTR);        This.context=context;    Init (); } public void setpercent (int percent){this.percent = percent; /*isshown (): Returns The visibility of this view and all of its ancestors*/if (Isshown ()) {/* Set the progress after restarting a            Times animation */curtime=0;        This.invalidate ();        }} public void Setprogesscolor (int mprogesscolor) {this.mprogesscolor = Mprogesscolor;        if (Isshown ()) {this.invalidate ();    }} public void Setcustomtext (String mcustomtext) {this.mcustomtext = Mcustomtext;    } private Handler Mhandler = new Handler (); Private Runnable manimation = new Runnable () {@Override public void run () {if (Curtime < dur                ation) {curtime++; /* cause redraw, call Ondraw,ondraw Last Call * mhandler.postdelayed (manimation, 20); Update progress bar, interface redraw * 20 ms each time, draw 10            Times, so the animation time is 200 milliseconds */CustomCircleBar.this.invalidate ();    }        }    }; private void Init () {/* data initialization, no default value when setting properties */percent =0;        Mprogesscolor=color.rgb (95,112,72);        mcustomtext= "Home";        Typedvalue=new Typedvalue ();    Context.gettheme (). Resolveattribute (R.attr.maintextclor,typedvalue,true);        } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        float mwidth = getwidth ();        float mheight = getheight (); /* Below is the setting for the progress bar brush *//** restores the paint to its default settings.        */Paintbar.reset ();        /* Ring Width 4 pixels */paintbar.setstrokewidth (4);        /* Hollow ring instead of filled frontal fan */Paintbar.setstyle (Paint.Style.STROKE);        Paintbar.setantialias (TRUE);        Paintbar.setcolor (Mprogesscolor);        /* Adjust the opacity, so that the border arc and progress bar distinguish between */Paintbar.setalpha (80);        /* Next is the setting of the text brush */painttext.settextsize (20);        Painttext.setcolor (Getresources (). GetColor (Typedvalue.resourceid));        Painttext.setstyle (Paint.Style.STROKE);        Painttext.setantialias (TRUE); /* Draw text from the middle */painttext.settextalign (Paint.Align.CENTER);        /* Measure Text Size */paint.fontmetrics FontMetrics = Painttext.getfontmetrics ();        /* Calculate Text Height */float textHeight = fontmetrics.bottom-fontmetrics.top;        /* Calculate the radius of the circle */Float radius = math.min (mwidth, mheight)/2-10; /*  ? Save: Used to save the state of the canvas. After save, you can call canvas's panning, indenting, rotating, trimming, cropping, and so on. Restore: The state used to restore the canvas before it is saved. Preventing the actions that are performed on the canvas after save has an impact on subsequent drawing.        */* Save canvas, Draw progress bar */Canvas.save (); /*cliprect: This method is used to crop the canvas, that is, after setting the display area of the canvas to call the ClipRect () method, only the cropped area will be displayed, except for the area that is not displayed */canvas.cliprect (0, 0, Mwidth, mHe        IGHT/2 + radius-textheight * 3/4);        /* For cliprect reasons, leave a gap below the outside of the ring to draw the text */canvas.drawcircle (MWIDTH/2, MHEIGHT/2, radius, paintbar);        /* Trigonometric calculation, half of the angle of the notch fan below/float Theta_offset = (float) math.acos ((RADIUS-TEXTHEIGHT/2)/radius);        /* Fan angle for large arcs */float Theta_full = 360-2 * THETA_OFFSET; /* The arc corresponding to the progress value is the angle */float thetaprocess = mdecelerateinterpolator.getinterpolation (1.0f * Curtime/duration) * percent * THETA_FULL/100;        /* Set progress value color is completely opaque */paintbar.setalpha (255);        Paintbar.setcolor (Mprogesscolor); /* Note the starting angle of the arc, the bottom because the display text causes the ring to break into an arc, the arc has the left and right two endpoints, the arc starts from the left endpoint */Canvas.drawarc (new RECTF (MWIDTH/2-radius, MHEIGHT/2-Radiu        S, Mwidth/2 + radius, MHEIGHT/2 + radius), theta_offset+90, Thetaprocess, False, Paintbar);        /* Restore Canvas */canvas.restore ();        /* Start Drawing Text */Painttext.settextsize (20);        FontMetrics = Painttext.getfontmetrics ();        float Textbaselineoffset = (fontmetrics.bottom-fontmetrics.top)/2-fontmetrics.bottom;        Canvas.drawtext (Mcustomtext, MWIDTH/2, MHEIGHT/2 + RADIUS-TEXTHEIGHT/2 + textbaselineoffset, paintText);        /* Draw percent */painttext.settextsize (mheight * 1/8);        FontMetrics = Painttext.getfontmetrics ();        Textbaselineoffset = (fontmetrics.bottom-fontmetrics.top)/2-fontmetrics.bottom; Canvas.drawtext ("%", MWIDTH/2, MHEIGHT/2 + radius/3 + textbaselineoffset, painttext);        /* Draw percent */painttext.settextsize (mheight * 3/8); Canvas.drawtext ("" + (int) (Percent*mdecelerateinterpolator.getinterpolation (1.0f * curtime/duration)), MWIDTH/2,        MHEIGHT/2, Painttext);    /*20 milliseconds after the animation */mhandler.postdelayed (manimation, 20); }}



Android custom control implements a circular progress bar with text and numbers

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.