Android custom controls to implement simple WordPad features _android

Source: Internet
Author: User
Tags getcolor

Let's take a look at the effect chart.

is simply to draw the content according to the track that the finger writes down

First, realize

The following points are mentioned in a previous article about the custom controls given by the Android official:

CREATE view

Handle layout of view

Draw View

Interacting with a user

Optimize a defined view

Just follow this step to complete today's custom control

1. Create View
the last part of this article, when it comes to creating a view, is to consider the simple declaration and use of custom attributes.

What are some custom properties for today's controls? To realize WordPad, there are three things: the color of WordPad, the color of the pen, and the thickness of the pen. So the next custom attribute.

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>

  <declare-styleable name= " Writingboardview ">
    <attr name=" boardbackground "format=" Color "></attr> <!--artboard color-->
    <attr name= "Paintcolor" format= "Color" ></attr> <!--brush color--> <attr name=
    "Paintwidth" format= "Dimension" ></attr> <!--brush width-->
  </declare-styleable>
</resources>

is defined in order to use the

 <?xml version= "1.0" encoding= "Utf-8"?> <relativelayout "xmlns:android=" /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.WritingBoardView android:layout_width= "Match_parent" Android:layout_ height= "Match_parent" custom:paintcolor= "@color/coloraccent" custom:boardbackground= "@color/colorprimary" Cust Om:paintwidth= "3DP"/> </RelativeLayout> 

The Boardbackground, Paintwidth, and Paintcolor properties are simply set

Use here only to notice namespaces, Android provides us with Android, we can customize our properties of the namespace
To be written as: xmlns: your name = "Http://schemas.android.com/apk/res-auto", where the Res-auto can be replaced by the package name of your control

The properties that are set in the XML layout file are to be acquired in the custom attribute, so we have to implement a AttributeSet construction method with the context

  private int mboardbackground;//artboard color private int mpaintcolor;//brush color private int mpaintwidth;//brush width private Path MP
  Ath
  Private Paint mpaint;//Brush Public Writingboardview (context context) {this (context,null);
  Public Writingboardview (context, AttributeSet attrs) {This (context, attrs,0); Writingboardview (context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, defstyleat
    TR);
  Init (context,attrs); } private void init (context Context,attributeset attrs) {TypedArray a = Context.obtainstyledattributes (attrs,r.sty Leable.
    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 (Typ
    Edvalue.complex_unit_dip,5,getresources (). Getdisplaymetrics ()); A. Recycle ();
    Mpaint = new Paint ();
    MPath = new Path ();
    SetBackgroundColor (Mboardbackground);
    Mpaint.setcolor (Mpaintcolor);
    Mpaint.setstrokewidth (Mpaintwidth);
    Mpaint.setstyle (Paint.Style.STROKE);
  Mpaint.setantialias (TRUE);
 }

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

By fixing the writing, simply getting to the custom attribute, and setting the background for the current view, and setting the style and color for paint. It is important to complete the path class here.

Let's introduce the path class first.

See comments on construction methods

/**
 * The Path class encapsulates compound (multiple contour) geometric paths
 * consisting of straight line segmen TS, quadratic curves, and cubic curves.
 * It can be drawn with canvas.drawpath (path, paint), either filled or stroked
 * (based on the paint ' s Style), or it CA n is used for clipping or to draw
 * text on a path.
 */Public
class Path {

  ...

} 

Basically, path encapsulates the geometry information that consists of a line and various curves. We can call canvas to draw something through the DrawPath method.
Our ultimate draw is to use DrawPath.

Path contains a number of methods for setting geometry such as Addrect, AddArc.
Today, the two ways to focus on:

 /**
   * 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-coordinate of the start of a new cont Our
   */public
  void MoveTo (float x, float y) {
    Native_moveto (mnativepath, x, y);
  

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

/**
   * Add a line "from" to "specified point" (x,y).
   * If no MoveTo () call has been made for this contour, the ' the '
   * 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
   */
   
    public void LineTo (float x, float y) {
    Issimplepath = 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, the layout of the processing view
because the 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 not appear when mode is unspecified.

There is no special treatment here.

3. Draw view and interact with users
since the control itself requires interaction to have an effect, the previous two steps are considered together.

It says canvas has a DrawPath method. DrawPath finally draws out what is actually looking at the information contained in the path.

We want to achieve real-time display of handwritten content, only to be in the sliding time to obtain the coordinates through the path of the LineTo method to connect the line 1.1 points.

It should be a new line when the finger is raised 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
  Boolean ontouchevent (Motionevent event) {
    float Touchx = Event.getx ();
    Float touchy = event.gety ();
    Switch (event.getaction ()) {case
      Motionevent.action_down:
        mpath.moveto (Touchx,touchy);//Reset the starting point of the line that will appear Break
        ;
      Case Motionevent.action_move:
        mpath.lineto (touchx,touchy);/connection break
        ;
      Case MOTIONEVENT.ACTION_UP: Break
        ;
    }
    Invalidate ()//notify the system to redraw return
    true;//to handle the current event
  }


Return true in Ontouch indicates that you want to handle the current event. And in each operation call invalidate to draw the interface, our OnDraw method only need to simply call DrawPath on the

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

Summarize

In fact, through the finger touch events to control the trajectory of the change, according to the fixed pattern, a simple custom control is done!

A simple WordPad is basically done, of course you are interested to expand it, plus at run time to change the color of the brush, artboard color. Add the ability to remove the font erase.

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.