Android Happy Snake Game Project development Tutorial-03 Virtual Direction key (ii) draw a triangle

Source: Internet
Author: User

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

First, draw the triangle

In the previous article, we have created a custom control Directionkeys class for the virtual direction key, which we continue below.

The background of the virtual direction key in this project is a rectangle of 4 triangles, which is actually a 4-triangle button.

The system comes with the button is rectangular, how to make a triangle button?

The first thing I need to know is that all the controls look like they are painted, not by hand, but by the program.

How to draw with the program?

Many technology platforms have drawing capabilities and are similar in use. Since all are object-oriented ideas, we can draw analogies with reality.

First we need a canvas, and then we need a paintbrush (paint) and a paint (color), which can be drawn in reality. But now is the process to draw, you have to tell the program what you want to draw. Because each person draws different things, and so on, so the painting of a variety of things, telling the way the program may also be different. We draw a triangle and choose to tell the program with the path object, which is detailed below. Then the program will draw it for you.

Understanding the basic process of drawing, we use code to implement.

In Android.view.View there is a method called OnDraw , we just rewrite (override) The parent class method, in the method to draw what we want.

When you enter OnDraw in Android studio, the following code is generated based on smart hints:

    /**      * Draw the graphics we need by overriding the OnDraw method of the parent     class     *@param  Canvas The canvas here is a rectangular canvas provided by the system, All we have to do is draw what we want on this canvas.      */     @Override    protectedvoid  onDraw (canvas canvas) {          Super. OnDraw (canvas);    }

As you can see from the code above, the OnDraw method gives us an object called canvas, canvas is a canvas, we can draw on it. Auto-generated "super.ondraw (canvas);" is to call the OnDraw method in the parent class, we can click to see.

    /** * Implement this to do      your drawing.     *     @param  canvas the canvas on which the background'll be drawn     *    / protectedvoid  onDraw (canvas canvas) {    }

found that the OnDraw method in the parent class is empty and can not be called.

Now that we have a canvas, we also need brushes. This is good, new one on the line.

        // Prepare the Brush        New Paint ();

What color should the brush be dipped in? Red, for example.

        // Set the color        of a brush Paint.setcolor (color.red);

The color here is an integer of type int and is a ARGB value. The system provides several common colors as constants, such as color.red=0xffff0000, you can also set a color according to your preferences.

Let's take the left triangle as an example.

Each pixel on the canvas has its coordinates, and the coordinate system origin is the upper-left corner of the canvas. To draw a triangle, you need to know the coordinates of the three vertices.

Set the canvas width to width, height is height;

The coordinates of the 4 vertex and center point of the canvas are:

Upper left Point 0,0
Lower left Dot 0,height
Upper right Point width,0
Lower right Point Width,height
Center Point WIDTH/2,HEIGHT/2

Then the three vertex coordinates of the left triangle are (0,0) (WIDTH/2,HEIGHT/2) (0,height)

The path object below has appeared. Path means a route, which tells the program to draw along a well-designed path. We know that triangles are made up of three straight segments, which are also designed in the program:

        //the width of the canvas        intwidth =canvas.getwidth (); //the height of the canvas        intHeight =canvas.getheight (); //Draw left ARROW key background triangle pathPath Pathleft =NewPath (); //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 ();

All the code for the Directionkeys class So far is as follows:

 PackageNet.chengyujia.happysnake;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.Path;ImportAndroid.util.AttributeSet;ImportAndroid.view.View;/*** Created by Chengyujia on 2016/8/19. * Virtual arrow keys on the screen*/ Public classDirectionkeysextendsView {//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); }    /*** Draw the graph we need by overriding the OnDraw method of the parent class *@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) {//the width of the canvas        intwidth =canvas.getwidth (); //the height of the canvas        intHeight =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*/        //Draw left ARROW key background triangle pathPath Pathleft =NewPath (); //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 (); //Prepare the BrushPaint paint =NewPaint (); //set the color of a brushPaint.setcolor (color.red); //set Brush to solid (default is solid, not set here or OK)Paint.setstyle (Paint.Style.FILL); //a solid red triangle was drawn according to the path design just now .Canvas.drawpath (pathleft, paint); }}
Second, the test

Now we can use our custom controls, as with the system's own control, except that the XML layout file needs to be labeled with the full name of the class, otherwise it will be an error.

We will modify the mainactivity layout file as follows:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns: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"Tools:context= "Net.chengyujia.happysnake.MainActivity">    <!--the custom control must use the full name of the class, or it will error.  -    <Net.chengyujia.happysnake.DirectionKeysAndroid:layout_width= "Match_parent"Android:layout_height= "Match_parent" /></LinearLayout>

Then run it as follows:

Well, this is the end of this article, the next chapter continues.

If you encounter problems, you can communicate in the comments below. ^_^

Android Happy Snake Game Project development Tutorial-03 Virtual Direction key (ii) draw a triangle

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.