Android Happy Snake Game Project development Tutorial-04 Virtual Direction key (iii) Triangle button effect

Source: Internet
Author: User

Overview and catalog of this series of tutorials: http://www.cnblogs.com/chengyujia/p/5787111.html

First, the knowledge point explanation

The appearance of the button changes when we click the button that comes with the system. In the last blog post we drew a triangle button, but the click can not change color, the following we will realize the click-Change function.

From the knowledge system we need to understand the following two points of knowledge

    • 1. How do I know if my finger clicked on our controls?

The solution is to rewrite the Ontouchevent method in view. When the finger touches our control, the system tells us this method. The method also has a parameter of type motionevent, through which we can know the specific type of the current touch event, such as pressing, moving, lifting, etc.
We can let the button display a darker color under normal conditions, and when pressed, a brighter color is displayed, and then it is lifted and restored to a darker color. This achieves the effect of clicking on the color change.

    • 2. How do I change color?

A method called invalidate is provided in view, and each time the method is called, the system calls the OnDraw method again to redraw the control. All we have to do is judge the current touch action in the OnDraw, and if it is pressed, draw a highlighted triangle, without touching or pressing it to draw a darker triangle.

Understanding the relevant knowledge points, the following we are implemented through the code.

Second, the Code implementation

The following is all the code for the current Directionkeys class:

 PackageNet.chengyujia.happysnake;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.graphics.Path;ImportAndroid.util.AttributeSet;Importandroid.view.MotionEvent;ImportAndroid.view.View;/*** Created by Chengyujia on 2016/8/19. * Virtual arrow keys on the screen*/ Public classDirectionkeysextendsView {//the color of the left triangle when pressed (lighter)    Private intLeftpressedcolor = 0xffff0000; //Left triangle normal display color (darker)    Private intLeftnormalcolor = 0xffaa0000; //Hand Touch the action of the screen, the initial value with an action value not used in a motionevent, such as 10, indicating that no touch screen action has occurred.     Private intAction =-10; //the width of the canvas    Private intwidth; //the height of the canvas    Private intheight; //draw the path of the left Triangle    PrivatePath Pathleft =NewPath (); //Brushes    PrivatePaint paint =NewPaint (); //whether the initialization method has been executed, ensuring that the initialization method executes only once.     Private BooleanInitdone =false; //only one parameter is constructed by the time we create an instance from the "new" keyword in the program.      PublicDirectionkeys (Context context) {Super(context); }    //There are two parameters that are constructed by invoking the system when an instance is created in an XML layout file.      PublicDirectionkeys (Context context, AttributeSet attrs) {Super(context, attrs); }    //Initialize Method    Private voidinit (canvas canvas) {/*get the length and width of the canvas*/width=canvas.getwidth (); Height=canvas.getheight (); /*(Tip: In a computer, the upper- left corner is generally used as the coordinate origin) the coordinates of the four vertices and center points on the canvas are as follows: Upper left point 0,0 lower left 0,height upper right point width,0 Lower right point Width,height center point WIDTH/2,HEIGHT/2*/        /*set the path data for the left Triangle*/        //start from the top left of the canvas.Pathleft.moveto (0, 0); //draw a straight line to the center point of the canvasPathleft.lineto (WIDTH/2, HEIGHT/2); //draw a straight line to the bottom left of the canvas.Pathleft.lineto (0, height); //automatically closes the drawing. Draw a straight line from the last point (bottom left) to the first point (top left). Pathleft.close (); }    /*** Draw the graph we need by overriding the OnDraw method of the parent class * This method is called by the system when the control is first displayed, and is called by the system after each call to the Invalidate method. *     * @paramCanvas Here is a rectangular canvas provided by the system, and all we have to do is draw what we want on this canvas. */@Overrideprotected voidOnDraw (canvas canvas) {if(!Initdone)            {init (canvas); //ensure that the initialization method executes only onceInitdone =true; }        if(Action = =Motionevent.action_down) {            //highlight when hand pressedPaint.setcolor (Leftpressedcolor); } Else {            //show darker colors when lifted without pressing or pressingPaint.setcolor (Leftnormalcolor); }        //draw the Left TriangleCanvas.drawpath (pathleft, paint); }    /*** If the hand touches our control, the system will tell us by this method *@paramthe event system gives us the touch events parameter *@returnReturns true if the touch event was processed by US and returns false instead. */@Override Public Booleanontouchevent (Motionevent event) {action=event.getaction (); //Action_down Indicates that the hand is pressed to the screen, action_up that the hand is lifted from the screen. We only deal with both of these actions.         if(action = = Motionevent.action_down | | action = =motionevent.action_up) {            //the Invalidate method is to tell the system that the current control needs to be redrawn, and the system calls the OnDraw method again to implement the redraw. invalidate (); return true; }        return false; }}

The above comment is more detailed, mainly on 3 methods OnDraw (Drawing), ontouchevent (Listening Touch event),invalidate (Let the system call OnDraw method for redrawing).

In addition, the path object and the Paint object can be initialized once, and it is not necessary to re-create each time OnDraw to improve program performance.

Third, the Operation effect

Show dark color when normal:

Show bright colors when pressed:

The test will find that clicking on the non-triangular area also changes color, because we have not yet judged the location of the click, this will be explained later.

Come here first, continue below. :)

Android Happy Snake Game Project development Tutorial-04 Virtual Direction key (iii) Triangle button effect

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.