Let's take a look at Android custom controls 2-simple WordPad controls, android2-

Source: Internet
Author: User
Tags getcolor

Let's take a look at Android custom controls 2-simple WordPad controls, android2-
Overview

In the previous article, we gave a general introduction to custom controls. Today we will learn to customize a simple WordPad control.

Let's take a look

It is simply to draw content based on the trajectory written by your fingers.

Implementation

As mentioned in the previous article, the custom control officially provided by android requires the following considerations:

Follow these steps to complete today's Custom Controls

1. Create a View

In the previous article, when creating a View, you should consider the simple declaration and use of custom attributes.

What are the Custom Attributes of today's controls? There are three things to implement a WordPad: The color of the Wordpad, the color of the pen, and the width of the pen. So next we will customize the attributes.

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <declare-styleable name = "WritingBoardView"> <attr name = "boardBackground" format = "color"> </attr> <! -- Canvas color --> <attr name = "paintColor" format = "color"> </attr> <! -- Paint color --> <attr name = "paintWidth" format = "dimension"> </attr> <! -- Paint width --> </declare-styleable> </resources>

It is defined to use

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns: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.WritingBoardView        android:layout_width="match_parent"        android:layout_height="match_parent"        custom:paintColor="@color/colorAccent"        custom:boardBackground="@color/colorPrimary"        custom:paintWidth="3dp"/></RelativeLayout>

BoardBackground, paintWidth, and paintColor attributes are simply set.

Here, you only need to pay attention to the namespace. android provides us with android, And we can customize the namespace of our properties.
Written as: xmlns: Your name = "http://schemas.android.com/apk/res-auto”, the res-autohere can be changed to the package name of your control

The attributes set in the XML layout file must be obtained in the Custom Attributes, so we must implement the constructor with Context and AttributeSet.

Private int mBoardBackground; // artboard color private int mPaintColor; // Paint brush color private int mPaintWidth; // Paint width private Path mPath; private Paint mPaint; // paint brush public WritingBoardView (Context context) {this (context, null);} public WritingBoardView (Context context, AttributeSet attrs) {this (context, attrs, 0 );} public WritingBoardView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); init (context, attrs);} private void init (Context context, AttributeSet attrs) {TypedArray a = context. obtainStyledAttributes (attrs, R. styleable. writingBoardView); mBoardBackground =. getColor (R. styleable. writingBoardView_boardBackground, Color. WHITE); mPaintColor =. getColor (R. styleable. writingBoardView_paintColor, Color. BLUE); mPaintWidth =. getDimensionPixelSize (R. styleable. writingBoardView_paintWidth, (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP, 5, getResources (). getDisplayMetrics ();. 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 constructor finally calls the init (context, attrs) method in the third constructor to obtain custom attributes and initialize some information.

The custom attributes are obtained through fixed writing and simple, and the background is set for the current view, and the style and color are set for the Paint. The Path class is very important to complete the WordPad.

First, we will introduce the Path class.

View comments of Constructor

/** * The Path class encapsulates compound (multiple contour) geometric paths * consisting of straight line segments, 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 can be used for clipping or to draw * text on a path. */public class Path {    ...}

 

In general, Path encapsulates geometric information composed of straight lines and various curves. We can call canvas to draw something through the drawPath method.
Our final draw is to use drawPath.

Path contains many ways to set the CT and addArc.
Today we will focus on two methods:

  /**     * 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 contour     */    public void moveTo(float x, float y) {        native_moveTo(mNativePath, x, y);    }

 

The moveTo method is used to set the initial position of the next line or image.

/**     * Add a line from the last point to the specified point (x,y).     * If no moveTo() call has been made for this contour, the first point is     * 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 use a real-line wordpad.

2. process View Layout

This custom control requires a piece of content as a Wordpad, so no special layout is needed, but the layout may not be displayed when the mode is UNSPECIFIED.

No special processing will be performed here.

3. Draw views and interact with users

Since the control itself requires interaction to produce results, the previous two steps are taken together.

As mentioned above, Canvas has a drawPath method. The drawPath finally draws out what is actually the information contained in the Path.

To display handwritten content in real time, we only need to use the lineTo method of Path to connect the coordinates obtained during the Sliding Process to 1.1 points.

When the finger is lifted and then dropped, it should be a new line. Therefore, when the finger is dropped, we need to call the moveTo method to set a starting point for the next track.

@ 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 break of the forthcoming line; case MotionEvent. ACTION_MOVE: mPath. lineTo (touchX, touchY); // link break; case MotionEvent. ACTION_UP: break;} invalidate (); // notification system re-painting return true; // process the current event}

 

In onTouch, return true indicates that the current event is to be processed. In addition, every operation calls invalidate to draw the interface. Our onDraw method only needs to simply call drawPath.

 @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        canvas.drawPath(mPath,mPaint);    }
Summary

In fact, it is through the touch of fingers to control the trajectory changes, according to the fixed mode, a simple custom control is achieved!

A simple wordpad is basically complete. Of course you are interested in extending it, plus changing the color of the paint brush and the color of the canvas during running. Adds the font erasure function.

Don't forget to give me a thumbs up comment! Haha

Source code download

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.