Learn about Android Custom Controls 2-Simple WordPad controls

Source: Internet
Author: User
Tags getcolor

Overview

In the previous article we introduced a general knowledge of custom controls. Learn to customize a simple WordPad control today.

Let's take a look.

is simply to draw the content according to the trajectory of your finger.

Realize

In the previous article, it was mentioned that the custom controls given by Android should consider the following points:

    1. CREATE view
    2. Working with the layout of a view
    3. Draw View
    4. Interacting with a user
    5. Optimize a defined view

Just follow this step to complete today's custom controls

1. Create View

In the previous article, it is important to consider the simple declaration and use of custom attributes when creating a view.

What are the custom properties of today's controls? To implement WordPad, it is actually three things: the color of the WordPad, the color of the pen, the thickness of the pen. So the next custom attribute.

<?XML version= "1.0" encoding= "Utf-8"?><Resources>    <declare-styleablename= "Writingboardview">        <attrname= "Boardbackground"format= "Color"></attr> <!--Artboard Color -        <attrname= "Paintcolor"format= "Color"></attr> <!--Brush Color -        <attrname= "Paintwidth"format= "Dimension"></attr> <!--Brush Width -    </declare-styleable></Resources>

Defined just to use the

<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Xmlns:custom= "Http://schemas.android.com/apk/res-auto"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.qiangyu.test.writingboardview.MainActivity">    <Com.qiangyu.test.writingboardview.view.WritingBoardViewAndroid:layout_width= "Match_parent"Android:layout_height= "Match_parent"Custom:paintcolor= "@color/coloraccent"Custom:boardbackground= "@color/colorprimary"Custom:paintwidth= "3DP"/></Relativelayout>

Simple settings for Boardbackground, Paintwidth, and Paintcolor properties

Use here only to pay attention to namespaces, Android provides us with Android, we can customize our properties namespace
The wording is: xmlns: you take the name = "Http://schemas.android.com/apk/res-auto", here the Res-auto can be replaced by your control's package name

The properties set in the XML layout file are to be obtained in the custom attribute, so we must implement the constructor with context, AttributeSet

   Private intMboardbackground;//Artboard Color    Private intMpaintcolor;//Brush Color    Private intMpaintwidth;//Brush Width    PrivatePath MPath; PrivatePaint Mpaint;//Brushes     PublicWritingboardview (Context context) { This(Context,NULL); }     PublicWritingboardview (Context context, AttributeSet attrs) { This(Context, attrs,0); }     PublicWritingboardview (context context, AttributeSet attrs,intdefstyleattr) {        Super(context, attrs, defstyleattr);    Init (context,attrs); } Private voidInit (Context context,attributeset attrs) {TypedArray a=context.obtainstyledattributes (Attrs,r.styleable.writingboardview); Mboardbackground=A.getcolor (R.styleable.writingboardview_boardbackground,color.white); Mpaintcolor=A.getcolor (R.styleable.writingboardview_paintcolor,color.blue); Mpaintwidth=a.getdimensionpixelsize (R.styleable.writingboardview_paintwidth, (int) Typedvalue.applydimension (typedvalue.complex_unit_dip,5, Getresources (). Getdisplaymetrics ());        A.recycle (); Mpaint=NewPaint (); MPath=NewPath ();        SetBackgroundColor (Mboardbackground);        Mpaint.setcolor (Mpaintcolor);        Mpaint.setstrokewidth (Mpaintwidth);        Mpaint.setstyle (Paint.Style.STROKE); Mpaint.setantialias (true); }

The above code ensures that each construction method eventually calls the Init (Context,attrs) method in the third constructor to get the custom properties and initialize some information

A fixed notation, a simple fetch to a custom property, and a background for the current view, a style and a color for paint are set. The path class is important for completing WordPad.

Let's start by introducing the path class

See comments on construction methods

/***/Publicclass  Path {    ...}

Basically, the path encapsulates the geometry information that consists of lines and various curves. We can call canvas to draw something through the DrawPath method.
Our final draw is the need for DrawPath.

Path contains many ways to set the geometry, such as Addrect, AddArc.
Here are two ways to focus today:

  /**      * Set The beginning of the next contour to the point (X, y).     *     @param  x The x-coordinate of the start of a new contour     @param  y the Y-coor Dinate of the start of a new contour     *    /publicvoid MoveTo (float< /c16>float  y) {        Native_moveto (mnativepath, x, y);    }

The MoveTo method is to set the next line or the first position of the graph.

/** * Add a line from the last point to the      specified point (x, y).     * If no MoveTo () call had been made for this contour, the first point was     * automatically set to (0,0).     *     @param  x the x-coordinate     of the end of a line@param  y the Y-coordinate     of the end of a line*    /publicvoid lineTo (float  float  y) {        false;        Native_lineto (Mnativepath, x, y);    }

The LineTo method simply adds a line from the previous point to the current point.

With these two methods, we can actually write the board.

2. Handle the layout of the view

Since this custom control itself requires a piece of content to be WordPad, there is no special layout to handle, but it may cause the layout to show up when mode is unspecified.

There is no special treatment here.

3. Draw a view, interact with the user

Because the control itself requires interaction to produce an effect, the previous two steps are considered together.

It says that canvas has a DrawPath method. DrawPath the final drawing of what is actually looking at the information contained in the path.

We want to achieve real-time display of handwritten content, only need to slide when the coordinates obtained through the path of the LineTo method to connect the line 1.1 points.

It should be a new line when the finger is lifted and then dropped, so we need to call the MoveTo method to set a starting point for the next trajectory when we fall.

@Override Public Booleanontouchevent (Motionevent event) {floatTouchx =Event.getx (); floatTouchy =event.gety (); Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:mPath.moveTo (touchx,touchy);//Reset the starting point of the line that will appear                 Break;  CaseMotionEvent.ACTION_MOVE:mPath.lineTo (touchx,touchy);//Connection                 Break;  Casemotionevent.action_up: Break; } invalidate ();//Notification System Redraw        return true;//to handle the current event}

Return true in Ontouch indicates that the current event is to be processed. And in every operation call invalidate to draw the interface, our OnDraw method just need to simply call DrawPath to be able to

@Override     protected void OnDraw (canvas canvas) {        super. OnDraw (canvas);        Canvas.drawpath (Mpath,mpaint);    }
Summarize

In fact, it is through the finger touch events to control the trajectory changes, in accordance with the fixed pattern, a simple custom control is done!

A simple WordPad is basically done, and of course you are interested in extending it, plus changing the color of the brush and the color of the artboard at run time. Added the ability to erase fonts.

Finally, don't forget to give me some comments support! Ha ha

SOURCE download

Learn about Android Custom Controls 2-Simple WordPad controls

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.