Android Custom view--Dynamic progress bar

Source: Internet
Author: User
Tags getcolor



This is to see Liangxiao's demo, according to his thinking himself wrote a, but I wrote this seemingly calculated or some problems, from the above diagram can be seen, the left, the top, the right side of the line will have been cut off part, have the hope to say, improve, this process is a bit tortuous, But still feel a lot of harvest. For example, through the animation to carry out dynamic display (previously done are updated through the handler, so now a thought to feel particularly good), as well as the starting and ending angle of the arc, the calculation of the rectangular area! About drawing we can be gradual, such as the first to draw a circle, and then draw the surrounding lines, and finally set the animation section. Not much to say, on the code.

Code Custom View
 Public  class colorprogressbar extends View{    //The following two lines in this demo does not work, just a few days ago to see someone else's code in accordance with a certain size, set other dimensions, automatically ignore or learn a little good//private int defaultstepindicatornum= (int) typedvalue.applydimension (typedvalue.complex_unit_dip,40, Getresources (). Getdisplaymetrics ());//int mcircleradius=0.28f*defaultstepindicatornum;    //width and height of layout    Private intMwidth;Private intMheight;//Diameter    Private intMdiameter= -;//Bottom Circle Brush    PrivatePaint MPAINTBG;//Brush with top-level circle    PrivatePaint Mpaintft;//brushes for surrounding lines    PrivatePaint Mpaintline;//length of outer line    Private intMLONGITEM=DIP2PX ( -);//Line and Circle spacing    Private intMDISTANCEITEM=DIP2PX (Ten);//The maximum width of the progress bar (take the bottom progress bar and the top-level progress bar width maximum)    Private intMprogresswidth;//The color of the bottom circle    Private intMbackcolor;//Top Circle Color    Private intMfrontcolor;//Bottom circle, top circle width    Private floatMbackwidth;Private floatMfrontwidth;//Set Progress    Private floatCurrentValue;//Show progress by animation    PrivateValueanimator animator;Private intCurvalue; Public Colorprogressbar(Context context) { This(Context,NULL,0); } Public Colorprogressbar(context context, AttributeSet attrs) { This(Context, Attrs,0); } Public Colorprogressbar(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);        TypedArray ta=context.obtainstyledattributes (Attrs, R.styleable.colorprogressbar);        Mbackcolor= Ta.getcolor (R.styleable.colorprogressbar_back_color, Color.Black);        Mfrontcolor=ta.getcolor (R.styleable.colorprogressbar_front_color,mbackcolor); Mbackwidth=ta.getdimension (r.styleable.colorprogressbar_back_width,dip2px (Ten)); Mfrontwidth=ta.getdimension (r.styleable.colorprogressbar_front_width,dip2px (Ten)); Mprogresswidth=mbackwidth>mfrontwidth? (int) Mbackwidth: (int) Mfrontwidth;//Pay attention to releasing resourcesTa.recycle ();    Init (); }/** * are brush initialization * /    Private void Init() {mpaintbg=NewPaint (Paint.anti_alias_flag);        Mpaintbg.setstrokewidth (Mprogresswidth);        Mpaintbg.setcolor (Mbackcolor);        Mpaintbg.setstrokecap (Paint.Cap.ROUND);        Mpaintbg.setstyle (Paint.Style.STROKE); mpaintft=NewPaint (Paint.anti_alias_flag);        Mpaintft.setcolor (Mfrontcolor);        Mpaintft.setstyle (Paint.Style.STROKE);        Mpaintft.setstrokewidth (Mfrontwidth);        Mpaintft.setstrokecap (Paint.Cap.ROUND); Mpaintline=NewPaint (Paint.anti_alias_flag);        Mpaintline.setcolor (Color.Black); Mpaintline.setstrokewidth (5); }@Override    protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {Super. Onmeasure (Widthmeasurespec, Heightmeasurespec);//width = height = (long pointer + pointer to disc spacing + progress bar thickness + radius)LOG.E ("Measurement Data","Longitem:"+mlongitem+"Mdistanceitem:"+mdistanceitem+"Mprogresswidth:"+mprogresswidth+"Mdiameter:"+mdiameter/2); Mwidth= (int)2* (mlongitem+mdistanceitem+mprogresswidth*2+mdiameter/2); Mheight= (int)2* (mlongitem+mdistanceitem+mprogresswidth*2+mdiameter/2); LOG.E ("Custom View","Height"+mheight+"width"+mwidth);    Setmeasureddimension (Mwidth,mheight); }@Override    protected void OnDraw(Canvas canvas) {Super. OnDraw (canvas);//Draw the bottom arc, the concrete calculation of the rectangle see pictureCanvas.drawarc (NewRECTF (mprogresswidth/2+mdistanceitem+mlongitem,mprogresswidth/2+mdistanceitem+mlongitem,mwidth-mprogresswidth/2-mdistanceitem-mlongitem,mheight-mprogresswidth/2-mdistanceitem-mlongitem),0, the,true, MPAINTBG);//Sweepgradient gradient=new sweepgradient ();        //Draw Edge linesCanvas.save (); Canvas.rotate (144, mwidth/2, mheight/2); for(intI=0; i<= -; i++) {Canvas.rotate (-9, mwidth/2, mheight/2);if(i%5==0) {Canvas.drawline (mwidth/2,5, mwidth/2, MLONGITEM,MPAINTBG); }Else{Canvas.drawline (mwidth/2, -, mwidth/2, Mlongitem,mpaintline); }} canvas.restore ();//Set a gradient for the brushSweepgradient sweepgradient=NewSweepgradient (mwidth/2, mheight/2, Color.red,color.yellow); Mpaintft.setshader (sweepgradient);//Draw top arc, currentvalue dynamic effect when changingCanvas.drawarc (NewRECTF (mprogresswidth/2+mdistanceitem+mlongitem,mprogresswidth/2+mdistanceitem+mlongitem,mwidth-mprogresswidth/2-mdistanceitem-mlongitem,mheight-mprogresswidth/2-mdistanceitem-mlongitem),135, CurrentValue,false, MPAINTFT); Mpaintft.settextsize ( -); Mpaintft.settextalign (Paint.Align.CENTER);//Draw textCanvas.drawtext (String.Format ("%.0f", CurrentValue), mwidth/2, mheight/2+ -, MPAINTFT);    Invalidate (); }/** * Set animation * @param Value * *     Public void Setcurrentvalue(floatValue) {//Currentvalue=value;Animator=valueanimator.offloat (Currentvalue,value); Animator.setduration ( the);        Animator.settarget (CurrentValue); Animator.addupdatelistener (NewValueanimator.animatorupdatelistener () {@Override             Public void onanimationupdate(Valueanimator valueanimator) {currentvalue= (float) Valueanimator.getanimatedvalue (); curvalue=curvalue/Ten;        }        });    Animator.start (); }Private int dip2px(floatDIP) {floatDensity=getcontext (). Getresources (). Getdisplaymetrics (). density;return(int) (dip*density+0.5f); }}
Rectangle calculation

Activity call
@Override    protectedvoidonCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.colorprogressbar);        mBtStart1= (Button) findViewById(R.id.bt1);        bar1= (ColorProgressBar) findViewById(R.id.cp1);        mBtStart1.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View view) {                bar1.setCurrentValue(270);            }        });    }
Custom properties
 <declare-styleable name="Colorprogressbar">       <attr name="Back_color" format="Color"></attr>        <attr name="Front_color" format="Color"></attr>        <attr name="back_width" format="Dimension"></attr>        <attr name="front_width" format="Dimension"></attr>    </declare-styleable>
Layout

Note: To add a single line of code (as) in order to use a custom attribute

xmlns:app="http://schemas.android.com/apk/res-auto"

Layout

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:app="Http://schemas.android.com/apk/res-auto"Android:layout_width="Match_parent"android:layout_height="Wrap_content"android:orientation="Vertical"> <button android:id="@+id/bt1"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:text="Start1"/> <com. Demo. Demo. Networkdemo. Colorprogressbar. Widgets. ColorprogressbarAndroid:id="@+id/cp1"Android:layout_width="232DP"android:layout_height="Match_parent"android:layout_gravity="Center_horizontal"App:back_color="@color/colorprimary"App:front_color="@color/coloraccent"Android:background="@mipmap/ic_launcher"/> </LinearLayout>

Android Custom view--Dynamic progress bar

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.