1. Introduce
We know that the Android game consists of two main aspects. On the one hand is the control class, which through some loops and monitoring mechanism to achieve. The other is the display class. In the real class, the most common is the View,view mechanism is more suitable for refreshing relatively slow applications, such as chess. The Surfaceview to be mentioned in this article is inherited from the view class. The advantage of Surfaceview is that it is possible to control the position, size and other properties of the object, the key is to provide the Surfaceholder class, using the Getholder method to obtain, the relevant canvas Lockcanvas (). The following is a brief introduction to the structure of the Surfaceview.
2. Code display
Here is the Surfaceview architecture, note comments!
public class Gameview extends Surfaceview implements Surfaceholder.callback {Surfaceholder surface;//new Surface to
Like public Gameview {super (context);
TODO auto-generated constructor stub surface = This.getholder (); Surface.addcallback (this);//Corresponds Surfacehoder.callback interface} public void CreateImage () {...} Build your own function to initialize the picture.
Bitmap objects such as public void OnDraw () {Canvas C =this.surface.lockcanvas ();
... surface.unlockcanvasandpost (c);........
//write your own function, using Canavas to draw the bitmap in the loop below.
The following three functions are automatically generated @Override public void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {//TODO auto-generated method stub length=arg2;//<span style= "Color: #ff0000" > Get high </span> on screen Width=arg3;//<span style= "color: #ff0000" > Get screen width. Really very practical </span>} @Override Public void surfacecreated (Surfaceholder arg0) {//TODO auto-generated method stub new
Thread (new Repaint ()). Start ();//<span style= "color: #ff0000" > Generally start looping threads here, not in constructors </span>}
@Override public void surfacedestroyed (Surfaceholder arg0) {//TODO auto-generated stub isrunning=false;//End Loop} Private class Repaint implements runnable{<spa
n style= "color: #ff0000" >//runnable loop thread, constantly refreshing redraw </span> public void run () {while (isrunning) {
CreateImage ();
OnDraw ();
//Refresh try {thread.sleep (50);
catch (Interruptedexception e) {e.printstacktrace (); }
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/