Android Use learning Drawing (canvas,paint) and gesture induction and its application (table tennis games)

Source: Internet
Author: User

As a novice without learning Android, the use of Android has recently been hard to learn outside of work.

This week I saw the pictures of Android. Mainly Canvas,paint and so on, feel the need to practice. Afternoon is free, just want to complete a table tennis game, is a consolidation of knowledge.

First of all, it is necessary to understand the frequently used classes that need to be mastered for Android drawing. Include canvas, like an artboard, where everything is drawn on top of it. Paint is the brush.       Use it to draw a variety of basic graphics and text. Canvas and paint are often used in ways that are not listed, and this stuff is everywhere on the web. There are two of these things. To realize the game, but also a gesture induction, for this game. You just need to identify the left and right shifts.

To do this, we need to use the Android Ongesturelistener interface and the Gesturedetector class.

Important methods such as the following are seen:

 Gesturedetector detector;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_start);    detector = new Gesturedetector (this, this);  } @Override public boolean ontouchevent (Motionevent event) {//TODO auto-generated method stub return    Detector.ontouchevent (event); } @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {//min. shift        Moving standard float minmove = 30; if ((E1.getx ()-E2.getx ()) > Minmove && math.abs (Velocityx) > Math.Abs (velocityy)) {Toast.maket        Ext (This, "Move to left", Toast.length_long). Show (); } else if ((E2.getx ()-E1.getx ()) > Minmove && math.abs (Velocityx) > Math.Abs (velocityy)) {Toas        T.maketext (This, "Move to Right", Toast.length_long). Show ();    } return false; }
We need to use the Ontouchevent () method called Gesturedetector in Ontouchevent, and only such a gesture-sensing interface is capable of being recalled. Of In the Onfling () method, we implement the extrapolation of left and right shifts.

Games such as the following are seen:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

The main areas to consider when implementing the game are the following:

1. How the state of the game describes the narrative. In detail, the state of the ball and racket.

2. How the view is dynamically refreshed

For question 1, the racket's state is relatively simple. Only left and right shift, set the x, Y coordinates of the racquet, using the step can be very good change, small ball words. Slightly troublesome. We need to use its x, y coordinates. X movement speed and Y movement speed to control its state. Hit left and right strong. X speed reversal, hit the racket or the top Y speed reversal, hit the bottom (not touching the racket) then the game is over.

For question 2, we need to start a timed refresh task, run the inferred current state at timed intervals, and then refresh the view based on the data.

The following is the main introduction of their own mini-game implementation. Surrogate mothers include the following classes, Tableplayactivity. Tableview,msgdefine,tableplaymodel. Tableplaycontroller.

Tableplayactivity such as the following:

Package Com.example.tableplay;import Android.support.v7.app.actionbaractivity;import Android.app.Service;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.os.vibrator;import Android.util.displaymetrics;import Android.util.log;import Android.view.gesturedetector;import Android.view.gesturedetector.ongesturelistener;import Android.view.menu;import Android.view.MenuItem;import Android.view.motionevent;import Android.view.window;import Android.view.windowmanager;import Android.widget.Toast     ;p ublic class Tableplayactivity extends actionbaractivity implements ongesturelistener{private Gesturedetector dector;    Private TableView MyView;    Private vibrator Vibrator;        @Override protected void OnCreate (Bundle savedinstancestate) {requestwindowfeature (window.feature_no_title);        Super.oncreate (savedinstancestate);        Init ();         Dector = new Gesturedetector (this, this); Vibrator = (Vibrator) Getsystemservice (service.vIbrator_service);        } private void Init () {MyView = new TableView (this);        Setcontentview (MyView); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN        );        WindowManager wm = Getwindowmanager ();        Displaymetrics metrics = new Displaymetrics ();        Wm.getdefaultdisplay (). Getmetrics (metrics);        LOG.I ("Dingbin", "width" + metrics.widthpixels + "height" + metrics.heightpixels);        Tableplaymodel.getinstance (). Mscreenx = Metrics.widthpixels;        Tableplaymodel.getinstance (). Mscreeny = Metrics.heightpixels; Tableplaymodel.getinstance (). Mrackety = Metrics.heightpixels-tableplaymodel.getinstance ().        Shift_distance;        Createhandler ();    Tableplaycontroller.getinstance (). Startgame (Mhandler);    } private Handler Mhandler; public void Createhandler () {Mhandler = new Handler () {@Override public void handlemessage ( Message msg) {super.handlemessage (msg);                            Switch (msg.what) {case msgdefine.msg_type_refresh:{myview.invalidate ();                        Break                        } Case msgdefine.msg_type_vibrotor:{Vibrator.vibrate (1000);                        Toast.maketext (tableplayactivity.this, "nice", Toast.length_short). Show ();                    Break                    } Default:break;    }                               }        }; } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the A        Ction Bar if it is present.        Getmenuinflater (). Inflate (R.menu.table_play, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks onThe Home/up button, so long/As you specify a parent activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item);    } @Override public boolean ontouchevent (Motionevent event) {return dector.ontouchevent (event); } @Override public Boolean ondown (Motionevent e) {//TODO auto-generated method stub return False    ; } @Override public void onshowpress (Motionevent e) {//TODO auto-generated method stub} @Over    Ride public boolean onsingletapup (Motionevent e) {//TODO auto-generated method stub return false; } @Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {//To    Do auto-generated method stub return false; } @Override public void onlongpress (Motionevent e) {//TODO auto-generated Method stub} @Override public Boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float ve        LOCITYY) {//min moving standard float minmove = 30;            if ((E1.getx ()-E2.getx ()) > Minmove && math.abs (Velocityx) > Math.Abs (velocityy)) {//left shift        Tableplaycontroller.getinstance (). Racketmoveleft ();             } else if ((E2.getx ()-E1.getx ()) > Minmove && math.abs (Velocityx) > Math.Abs (velocityy)) {//Right Shift        Tableplaycontroller.getinstance (). Racketmoveright ();        }//Redraw view myview.invalidate ();    return false; }}
In the Tableplayactivity class. We mainly realize the inference of gesture induction and the processing of handler message, in addition, the width and height of the screen are obtained in the initialization.
TableView is our basic drawing class, and in its OnDraw method, we achieve the redrawing of small balls and rackets, such as the following code:

Package Com.example.tableplay;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.paint.style;import Android.util.Log;    Import Android.view.view;import Android.widget.toast;public class TableView extends view{private paint paint;    Private Context Mcontext;        Public TableView (Context context) {super (context);        Mcontext = context;        Create Brush paint = new paint ();        Paint.setantialias (TRUE);    Paint.setstyle (Style.fill);        } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);        Tableplaymodel data = Tableplaymodel.getinstance ();            if (data.isgameover) {paint.settextsize (80);            Paint.setcolor (Color.Blue);            Setbackgroundresource (R.drawable.game_over);        Canvas.drawtext ("Game is over!", DATA.MSCREENY/2, paint); } else {//Draw racket Paint.setcolor (CoLor.            GREEN); Canvas.drawrect (Data.mracketx, data.mrackety, Data.mracketx + data. Racket_width, Data.mrackety + data.            Racket_height, paint);            Draw the ball paint.setcolor (Color.gray);        Canvas.drawcircle (DATA.MBALLX, data.mbally, Data.mballradius, paint); }    }}
Next is the data class Tableplaymodel, which primarily caches the data we need to use, including the game states and constants we all need to use. The code is as follows:

Package Com.example.tableplay;import Java.util.random;import Android.util.log;public class Tableplaymodel {private St    atic Tableplaymodel minstance = null;    Screen width and height public int mscreenx;    public int mscreeny;    Width and height of the racquet public final int racket_width = 180;    public final int racket_height = 25;    The length of the racket move public int mracketstep = 150;    The horizontal and vertical position of the racquet public int mracketx = 100;    public int mrackety;    Private random Rand = new Random ();    Radius of the ball public int mballradius = 35;    The x, y coordinates of the ball are public int mballx = Rand.nextint (200) + 20;    public int mbally = Rand.nextint (500) + 20;    Small ball x, y movement speed public int mballyspeed = 28;    Private double mxrate = rand.nextdouble ()-0.5;        public int mballxspeed = (int) (Mballyspeed * mxrate * 2);    Refresh interval ms public int mtimeinterval = 100;        Refresh delay ms public int mtimedelay = 0;        public final int shift_distance = 200;        public Boolean isgameover = false; public static TABLEPLAymodel getinstance () {if (minstance = = null) {synchronized (Tableplaymodel.class) {if (minstance = = null)                    {log.i ("Dingbin", "Tableplaymodel.getinstance ()");                Minstance = new Tableplaymodel ();    }}} return minstance; }}
Next is the most important control class Tableplaycontroller, and our core logic is in that class. in detail. is to start the timer running task, according to the current state to run the ball's motion position, update the ball's coordinates. and notifies the view refresh interface. The code is as follows:

Package Com.example.tableplay;import Java.util.timer;import Java.util.timertask;import android.os.Handler;import Android.os.message;import Android.util.log;import Android.widget.toast;public class TablePlayController {private    static Tableplaycontroller minstance = null;    Private Tableplaymodel data = Tableplaymodel.getinstance ();            Private Tableplaycontroller () {} public static Tableplaycontroller getinstance () {if (minstance = = null) { Synchronized (Tableplaycontroller.class) {if (minstance = = null) {return NE                W Tableplaycontroller ();    }}} return minstance;        } public void Startgame (final Handler Handler) {log.i ("Dingbin", "startgame");        data = Tableplaymodel.getinstance ();        LOG.I ("Dingbin", data.tostring ());        Final Timer timer = new timer ();    Timer.schedule (New TimerTask () {@Override public void run () {            Assuming that the left and right borders are met if (data.mballx <= Data.mballradius | | data.mballx >= DATA.MSCREENX-DATA.MB                Allradius) {data.mballxspeed =-data.mballxspeed; }//Assuming that the position is below the height of the racquet but not within the range of the racquet, the match ends if (data.mbally > Data.mrackety && (data.mballx                        < Data.mracketx | | DATA.MBALLX > Data.mracketx + data.                    Racket_width)) {timer.cancel ();                Data.isgameover = true;                } else if (data.mbally <= data.mballradius) {data.mballyspeed =-data.mballyspeed; } else if ((data.mballx >= data.mracketx && data.mballx <= data.mracketx + data.                    Racket_width && (data.mbally + data.mballradius) >= data.mrackety) {                    Data.mballyspeed =-Data.mballyspeed;          Message msg = Message.obtain (handler);          Msg.what = Msgdefine.msg_type_vibrotor;                Msg.sendtotarget ();                }//Ball coordinate change data.mballx + = Data.mballxspeed;                Data.mbally + = Data.mballyspeed;                Send Message msg = Message.obtain (handler);                Msg.what = Msgdefine.msg_type_refresh;            Msg.sendtotarget ();    }}, Data.mtimedelay, Data.mtimeinterval);            }/* * Racquet Left shift */public void Racketmoveleft () {if (Data.mracketx >= data.mracketstep) {        Data.mracketx + =-data.mracketstep;        } else {data.mracketx = 0; }/* * Racket right SHIFT */public void Racketmoveright () {if (Data.mracketx + data.        Racket_width) < Data.mscreenx) {data.mracketx + = Data.mracketstep; } else {data.mracketx = Data.mscreenx-data.        Racket_width; }    }}
In order to achieve better results, we will shake the ball when the success (need to add <uses-permission android:name= in Androidmanifest.xml "Android.permission.VIBRATE "/>), and to play toast to congratulate.

The last thing left is the information data class Msgdefine. The type of data that is stored. In detail, contains the refresh message and the vibrate message type, code such as the following:

Package Com.example.tableplay;public class Msgdefine {public    static final int msg_type_refresh = 1;    public static final int msg_type_vibrotor = 2;}
The above is the small game all the code implementation, do more rough, hope that there is a chance to optimize the next.





Android Use learning Drawing (canvas,paint) and gesture induction and its application (table tennis games)

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.