Android Notes custom view making dial interface

Source: Internet
Author: User

Preface

recently I have been on a custom view bar, even a little addicted to being possessed. As a rookie I naturally have to consult a large number of materials, learning the Code of the gods, this is not the first two days in the Guo Shen in the public to push a piece of custom control article-step by step to achieve a beautiful clock interface. is suitable for me this kind of rookie to study, idle nothing, I almost according to gourd painting Scoop also wrote a custom dial view, now purely the most notes recorded. First show the following:



Get down to the chase.

Custom Dial Properties

First, add the dial custom attribute to the Attrs file.

    <declare-styleable name= "Watchview" > <attr name= "Watchradius" format= "Dimension"/> Dial radius <attr name= "watchpadding" format= "Dimension"/>//Dial relative control border distance <attr Nam E= "watchscalepadding" format= "Dimension"/>//scale relative to dial distance <attr name= "Watchscalecolor" format= "Colo R|reference "/>//General scale color <attr name=" watchscalelength "format=" dimension|reference "/>//General scale Length <attr name= "Watchhourscalecolor" format= "dimension|reference"/>//hourly scale color <attr name= "WatchHour Scalelength "format=" dimension|reference "/>//hourly tick length <attr name=" Hourpointcolor "format= [color|reference]/&G            T Hour hand color <attr name= "hourpointlength" format= "dimension|reference"/>//hour-length <attr name= "Minutep Ointcolor "format=" color|reference "/>//minute hand color <attr name=" minutepointlength "format=" Dimension|refere nCE "/>    Minute hand length <attr name= "Secondpointcolor" format= "color|reference"/>//second hand color <attr name= "sec Ondpointlength "format=" dimension|reference "/>//second hand length <attr name=" timetextsize "format=" Dimension|referen Ce "/>//Dial font size <attr name=" Timetextcolor "format=" color|reference "/>//Dial Font Color < /declare-styleable>

get custom properties in Custom view construction methods

The attribute variables are declared as follows:

<span style= "FONT-SIZE:14PX;"    >/** Dial margin */private float mwatchpadding = 5;    /** dial and scale margin */private float mwatchscalepadding = 5;    /** Dial radius */private float Mwatchradius = 250;    /** Dial Scale length */private float mwatchscalelength;    /** Dial Scale color */private int mwatchscalecolor = Color.Black;    /** table Consolidation Point Scale length */private float mhourscalelength = 8;    /** table Consolidation Point scale color */private int mhourscalecolor = Color.Blue;    /** Dial Clock color */private int mhourpointcolor = Color.Black;    /** Dial Hand length */private float mhourpointlength = 100;    /** dial minute hand color */private int mminutepointcolor = Color.Black;    /** dial minute hand length */private float mminutepointlength = 130;    /** Dial Second color */private int msecondpointcolor = color.red;    /** dial Second hand length */private float msecondpointlength = 160;    /** Dial Tail length */private float mendpointlength;    /** Dial Digital color */private int mtimetextcolor = Color.Black; /** Dial Digit size */private int mtimetextsize = 15;</SPAN> 

Get custom properties in the constructor method type

<span style= "FONT-SIZE:14PX;"        > Public Watchview (Context context, AttributeSet Attrs) {Super (context, attrs);        TypedArray array = context.obtainstyledattributes (Attrs,r.styleable.watchview);        int n = array.getindexcount ();            for (int i = 0;i<n;i++) {int attr = Array.getindex (i); Switch (attr) {Case R.styleable.watchview_watchradius:mwatchradius = array.getdimension                    Pixelsize (attr,myutil.dip2px (context,60));                Break Case r.styleable.watchview_watchpadding:mwatchpadding = array.getdimensionpixelsize (attr,MyUtil.dip2px                    (context,5));                Break Case r.styleable.watchview_watchscalepadding:mwatchscalepadding = array.getdimensionpixelsize (Attr,MyU                    TIL.DIP2PX (context,3));                Break Case r.styleable.watchview_watchscalelength:mwatchscalelength = array.geTdimensionpixelsize (attr,myutil.dip2px (context,5));                Break Case R.styleable.watchview_watchscalecolor:mwatchscalecolor = Array.getcolor (attr, Color.parsecolor ("#                    50000000 "));                Break Case r.styleable.watchview_watchhourscalelength:mhourscalelength = array.getdimensionpixelsize (attr,My                    UTIL.DIP2PX (context,10));                Break                    Case R.styleable.watchview_watchhourscalecolor:mhourscalecolor = Array.getcolor (Attr,color.black);                Break Case r.styleable.watchview_hourpointlength:mhourpointlength = Array.getdimensionpixelsize (attr,MyUtil.                    DIP2PX (context,35));                Break                    Case R.styleable.watchview_hourpointcolor:mhourpointcolor = Array.getcolor (Attr,color.black);                Break Case R.styleable.watchview_minutepointlengtH:mminutepointlength = Array.getdimensionpixelsize (attr,myutil.dip2px (context,40));                Break                    Case R.styleable.watchview_minutepointcolor:mminutepointcolor = Array.getcolor (Attr,color.black);                Break Case r.styleable.watchview_secondpointlength:msecondpointlength = array.getdimensionpixelsize (Attr,MyU                    TIL.DIP2PX (context,50));                Break                    Case R.styleable.watchview_secondpointcolor:msecondpointcolor = Array.getcolor (Attr,color.blue);                Break Case r.styleable.watchview_timetextsize:mtimetextsize = array.getdimensionpixelsize (attr,MyUtil.dip2px                    (context,15));                Break                    Case R.styleable.watchview_timetextcolor:mtimetextcolor = Array.getcolor (Attr,color.black);            Break }} Array. Recycle (); }</span>

Set Control size

Here is of course the rewrite Onmeasure method, here we deal with the simple point, as shown in the code below, when we set the width of the control to WRAP_ Content (that is, measurespec.unspecifed), we set the width height to the default value (wrapcontentsize) and the disk radius + disk margin (mwatchradius+mwatchpadding) to take the maximum value, In other cases, the system will pick up the value. Of course, as a strict control, the only way to deal with this is certainly not possible. Project, we need to modify the code to fit our needs according to our own requirements.

<span style= "FONT-SIZE:14PX;" >    @Override    protected void onmeasure (int widthmeasurespec, int. heightmeasurespec) {        int Wrapcontentsize = +;        int widthsize = measurespec.getsize (widthmeasurespec);        int widthmode = Measurespec.getmode (widthmeasurespec);        int heightsize = measurespec.getsize (heightmeasurespec);        int heightmode = Measurespec.getmode (heightmeasurespec);        if (Widthmode = = Measurespec.unspecified && Heightmode = = measurespec.unspecified) {            wrapcontentsize = (int) Math.max (wrapcontentsize,mwatchradius+mwatchpadding);            Setmeasureddimension (wrapcontentsize,wrapcontentsize);        } else {            setmeasureddimension (widthsize,heightsize);        }    } </span>

overriding the OnDraw method

Come to the most critical really draw the dial moment. Step-by-step, first initialize our brushes (my habit, write a initpaint method)

<span style= "FONT-SIZE:14PX;" >    private void Initpaint () {        mpaint = new Paint ();        Mpaint.setantialias (true);        Mpaint.setcolor (color.white);        Mpaint.setstyle (Paint.Style.FILL);    } </span>
In order not to repeat, to facilitate understanding, I directly show the code, in the code to explain

Before we start the painting, we move the brush to the center point of the control, as follows:

<span style= "FONT-SIZE:14PX;" > @Override    protected void OnDraw (canvas canvas) {        canvas.translate (getwidth ()/2,getheight ()/2);    } </span>
The first step is to draw the dial
<span style= "FONT-SIZE:14PX;" >    /**     * Draw Dial     * @param canvas */    private void Paintwatchboard (canvas canvas) {        initpaint ();        Canvas.save ();        Canvas.drawcircle (0,0,mwatchradius,mpaint); Draw Disc        Canvas.restore ();    } </span>
Note: Before each drawing, call the Canvas.save () method, save the brush properties, and then call the Canvas.restore () method after painting to reset the brush properties
There is no one to show after each painting.

The second step, draw the scale + hour time number (the scale starts from the 12 point direction to draw)

<span style= "FONT-SIZE:14PX;" >/** * Draw scale and the hour number * @param canvas */private void Paintscale (canvas canvas) {int linelength;//        Tick line length canvas.save (); for (int i = 0;i<60;i++) {if (i%5 = = 0) {///hour scale under brush-related properties Mpaint.setstrokewidth (myutil.dip2px (get                Context (), 1.5f));                Mpaint.setcolor (Mhourscalecolor);                LineLength = myutil.dip2px (GetContext (), 8);                Canvas.drawline (0,-mwatchradius+mwatchscalepadding,0,-mwatchradius+mwatchscalepadding+linelength,mpaint);                Mpaint.setcolor (Mtimetextcolor);                Mpaint.settextsize (mtimetextsize); Canvas.drawtext (mtimes[i/5],-mtimetextsize/2,-mwatchradius+mwatchscalepadding + lineLength+mTimeTextSize,mPaint)                ;//The position of the hour is marked on the hour time number}else {//non-hour scale under the brush related properties Mpaint.setstrokewidth (myutil.dip2px (GetContext (), 0.8f));                Mpaint.setcolor (Mwatchscalecolor); LineLength = myutil.dip2px (getContext (), 5);            Canvas.drawline (0,-mwatchradius+mwatchscalepadding,0,-mwatchradius+mwatchscalepadding+linelength,mpaint);    } canvas.rotate (6);//each time a tick line is drawn, the brush rotates 6 degrees clockwise (360/60, the angle difference between two ticks is 6 degrees)} canvas.restore (); }</span>
which, on the hour, I used Roman numerals to denote

<span style= "FONT-SIZE:14PX;" >private string[] Mtimes = {"XII", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "XI"};</span>

Step three, draw the hour, minute, seconds, and other modifiers

Given the different lengths of the hour, minute and second hand, I have deliberately defined three brushes to draw the hour, minute and second hand separately.

Similarly, the pointer brush is initialized first:

<span style= "FONT-SIZE:14PX;" >/**     * Initialize pointer *     /    private void Initpointpaint () {        mhourpaint = new Paint ();        Mhourpaint.setantialias (true);        Mhourpaint.setstyle (Paint.Style.FILL);        Mhourpaint.setstrokewidth (+);        Mhourpaint.setcolor (Mhourpointcolor);        Mminutepaint = new Paint ();        Mminutepaint.set (mhourpaint);        Mminutepaint.setstrokewidth (n);        Mminutepaint.setcolor (Mminutepointcolor);        Msecondpaint = new Paint ();        Msecondpaint.set (mhourpaint);        Msecondpaint.setstrokewidth (7);        Msecondpaint.setcolor (Msecondpointcolor);        Mendpointlength = MWATCHRADIUS/6; (modified part) The tail length of the pointer, defined as One-sixth}</span> of the dial radius    
Draw Pointer

<span style= "FONT-SIZE:14PX;"        >/** * Draw pointer * @param canvas */private void Paintpoint (canvas canvas) {initpointpaint (); Calendar C = calendar.getinstance ();        Take the current time int hour = C.get (Calendar.hour_of_day);        int minute = C.get (Calendar.minute);        int second = C.get (Calendar.second);        Draw the hour canvas.save ();        Canvas.rotate (HOUR*30);        Canvas.drawline (0,0,0,-mhourpointlength,mhourpaint);        Canvas.drawline (0,0,0,mendpointlength,mhourpaint);        Canvas.restore ();        Draw the minute hand canvas.save ();        Canvas.rotate (MINUTE*6);        Canvas.drawline (0,0,0,-mminutepointlength,mminutepaint);        Canvas.drawline (0,0,0,mendpointlength,mminutepaint);        Canvas.restore ();        Draw the second hand canvas.save ();        Canvas.rotate (SECOND*6);        Canvas.drawline (0,0,0,-msecondpointlength,msecondpaint);        Canvas.drawline (0,0,0,mendpointlength,msecondpaint);    Canvas.restore (); }</span>
OK, it's almost all there, just call it in the OnDraw.

<span style= "FONT-SIZE:14PX;" > @Override    protected void OnDraw (canvas canvas) {        canvas.translate (getwidth ()/2,getheight ()/2);        Paintwatchboard (canvas); Draw Dial        Paintscale (canvas),//Draw scale        paintpoint (canvas),//Draw pointer        canvas.drawcircle (0,0,15,msecondpaint); For the sake of aesthetics, it also made the dial closer to what we showed in life, and I drew a big red dot in the center of the disc. Decoration seconds        postinvalidatedelayed (1000);//Draw once every second    }</span>
(⊙v⊙) Well, the custom view is done, so let's call it in the layout file to see the effect.

<span style= "FONT-SIZE:14PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "    xmlns:zhusp=" Http://schemas.android.com/apk/res-auto "    android:layout_width=" Match_parent "    android:layout_height= "match_parent"    android:background= "@color/coloraccent" >    < Com.wondertek.propertyanimatordemo.WatchView        android:layout_width= "wrap_content"        android:layout_height = "Wrap_content"        zhusp:timetextsize= "20DP"        zhusp:watchradius= "150DP"        zhusp:hourpointlength= "80DP"        zhusp:minutepointlength= "100DP"        zhusp:secondpointlength= "115DP"/></relativelayout></ Span>

Finally, my static effect here is this:


End

Finished, finally to add some force lattice, learning, gradual. Now that I have chosen the distance, I will only take the hardships


Reference: Custom View New Combat-step-by-step implementation of the exquisite Watch interface


Android Notes custom view making dial interface

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.