View class and Surfaceview detailed description

Source: Internet
Author: User
Tags gety

View classes and Surfaceview are detailed:

View class:

The view class is a super class for Android, which contains almost all screen types, and each view has a canvas for painting, which can be expanded arbitrarily. The layout view can be done via the Android XML. In game development, of course, you can also customize the view, so that the function of the canvas to better meet our needs in the game development, in Android, any view class only need to rewrite the OnDraw method to implement interface display, custom view can be a complex 3D implementation, It can also be a simple form of text.

The most important thing in the game is to interact with the players, such as keyboard input, stylus clicks and other events, and how can we handle these events? OnKeyUp (Push-button), OnKeyDown (Press-button), ookeymultiple (called when multiple events occur consecutively), Ontouchevent (touch events), and so on, can easily handle event messages within the game. So when you inherit view, you need to reload these methods, and when there are keys bouncing or pressing, the key code is automatically transferred to the appropriate method to handle.

The core of the game is the constant drawing and refresh of the interface, which we already know and need to draw using the OnDraw method. Let's examine how to refresh the interface. The Invalidate method is provided in Android to refresh the interface, noting that the Invalidate method cannot be called directly in the thread because it violates the single-threaded model, the Android UI operation is not threaded, and these operations must be performed in the UI thread, So the most common approach in Android is to use handler to implement UI thread updates.

The following is an update of the interface in Android by a rectangle that constantly transforms the color on the screen.

Create a new class to extend to the view class

public class Gameview extends view{

public int count = 0; Conversion to control color
public static int y=100;//the y-coordinate of the rectangle
public static int x=100;//The x-coordinate of the rectangle

Public Gameview (Context context) {
Super (context);
}

Overriding the OnDraw method for drawing the interface
public void OnDraw (canvas canvas) {
if (count<100) {
count++;
}else{
count=0;
}
Paint paint = new paint ();
Switch (count%4) {
Case 0:
Set Brush color
Paint.setcolor (color.red);
Break
Case 1:
Paint.setcolor (Color.Blue);
Break
Case 2:
Paint.setcolor (Color.yellow);
Break
Case 3:
Paint.setcolor (Color.green);
Break
}
Draw a rectangle
Canvas.drawrect (x,y,300+x,y+300, paint);
}
}

The above class is mainly used to draw the interface, below we also need an operation to control the entire application, such as: Event processing, update frequency of the class, which requires the implementation of an activity class.

public class Mainactivity extends Activity {

A hexadecimal number that determines whether the received information is the information we want.
private static final int REFRESH = 0X00000001;
Declaring a Gameview class object
Private Gameview gameview = null;;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Set Untitled Mode
Requestwindowfeature (Window.feature_no_title);
Instantiating a Gameview object
Gameview = new Gameview (this);
Setcontentview (Gameview);

Start a thread
New Thread (New MyThread ()). Start ();
}

Declares and creates a handler object to accept the message
Handler Handler = new Handler () {

Processing after receiving a message
public void Handlemessage (Message msg) {
Switch (msg.what) {
Case Mainactivity.refresh:
Gameview.invalidate ();
}
Super.handlemessage (msg);
}
};

/*class MyThread implements runnable{
public void Run () {
while (! Thread.CurrentThread (). isinterrupted ()) {
Message message = new Message ();
Message.what = Mainactivity.refresh;
Send Message
Handler.sendmessage (message);
}
try{
Thread.Sleep (1000);
}catch (Interruptedexception e) {
Thread.CurrentThread (). interrupt ();
}
}
}*/

Wirelessly also provides the Postinvalidate () method to update the interface, which is simple to use, can be updated directly in the thread, can update the interface in the same way, and does not require handle to accept messages
Class MyThread implements runnable{
public void Run () {
while (! Thread.CurrentThread (). isinterrupted ()) {
try{
Thread.Sleep (1000);
}catch (Interruptedexception e) {
Thread.CurrentThread (). interrupt ();
}
Gameview.postinvalidate ();
}
}
}

public boolean onKeyDown (int keycode,keyevent event) {
Switch (keycode) {
Case Keyevent.keycode_dpad_down:
Gameview.y + = 10;
Break
Case Keyevent.keycode_dpad_left:
gameview.x-= 10;
Break
Case Keyevent.keycode_dpad_right:
gameview.x + = 10;
Break
Case KEYEVENT.KEYCODE_DPAD_UP:
GAMEVIEW.Y-= 10;
Break
}

return false;
}

@Override
public boolean ontouchevent (Motionevent event) {
if (Event.getaction ()!=motionevent.action_down) {
return false;
}
gameview.x= (int) event.getx ();
gameview.y= (int) event.gety ();
Return Super.ontouchevent (event);
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}

}

Surfaceview Class Introduction:

The view class is only suitable for the development of some games that require a passive update of the interface, such as chess games, but when the need to develop complex games, and the performance of the game is more efficient, the view class can not meet the requirements, then need to surfaceview class for development. For example, high-speed games, you can use double-buffered display, the game's background, characters, animations need to be drawn on a canvas (canvas), and Surfaceview can directly access a canvas, The Surfaceview class is available for applications that require direct portraiture rather than using widgets. An important concept in the Android graphics system is Surface,view, and its subclasses such as (Textview,button) are to be painted on surface, each surface creates a canvas object (but the properties change constantly), Used to manage the operation of view on surface.

When you use Surfaceview to develop a game, it is important to note that when you use it to draw, it usually appears at the top level, and it needs to be created, destroyed, and monitored when the situation changes. This requires the implementation of the Surfaceholder.callback interface, and if you want to crop the drawn canvas, control its size by Surfaceholder to complete the processing. In the program, the Surfaceholder object needs to be obtained through the Getholder method, and the Addcallback method is required to add a "callback function".

Surfacechanged: Fires when the size of your surface changes

Surfacecreated: Fires when you create your surface

Surfacedestroyed: Fires when you destroy your surface.

Addcallback: Add a callback function to Surfaceview

Lockcanvas: Lock the canvas before drawing, you must lock the canvas to get the current canvas object

Unlockcanvasandpost: Unlock canvas, after drawing is complete, you need to unlock the canvas to display it

Removecallback: Removing the callback function from the Surfaceview

The obvious difference between surfaceview and view is that Surfaceview does not need to update the view through threads, but must lock the canvas by Lockcanvas, get the canvas object, and then draw on the canvas when the drawing is complete. It is necessary to unlock the canvas through the Unlockcanvasandpost method, so that it can be displayed on the screen, like Surfaceview and view event handling, which is not much of an introduction.

The following program implements a constantly changing color circle that is used to analyze the development of games through the Surfaceview class.

public class Mysurfaceview extends Surfaceview implements surfaceholder.callback,runnable{

public static float x = 200;
public static float y = 200;
Private surfaceholder surfaceholder= null;
Private Boolean mloop = false;
Private int count = 0;

Public Mysurfaceview (context context) {
Super (context);
Surfaceholder = This.getholder ();
Surfaceholder.addcallback (this);
Mloop = true;


}

@Override
public void Run () {
while (Mloop) {
try{
Thread.Sleep (10);
}catch (Exception e) {
E.printstacktrace ();
}
Synchronized (Surfaceholder) {
Draw ();
}
}
}

public void Draw () {
Canvas canvas = Surfaceholder.lockcanvas ();
if (canvas = = NULL | | surfaceholder = = NULL) {
Return
}
if (count <100) {
Count + +;
}else{
Count = 0;
}

Paint paint = new paint ();
Paint.setcolor (Color.Black);
Canvas.drawrect (0,0,this.getwidth (), getheight (), paint);
Switch (count%4) {
Case 0:
Paint.setcolor (color.red);
Break
Case 1:
Paint.setcolor (Color.Blue);
Break
Case 2:
Paint.setcolor (Color.yellow);
Break
Case 3:
Paint.setcolor (Color.green);
Break
}
Canvas.drawcircle (x, y, +, paint);
Surfaceholder.unlockcanvasandpost (canvas);
}

@Override
public void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {
New Thread (This). Start ();
}

@Override
public void surfacecreated (Surfaceholder arg0) {
TODO auto-generated Method Stub

}

@Override
public void surfacedestroyed (Surfaceholder arg0) {
Mloop = false;
}

}

Activity class:

public class Mainactivity extends Activity {

Private Mysurfaceview mysurfaceview= null;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Mysurfaceview = new Mysurfaceview (this);
Setcontentview (Mysurfaceview);
}

public boolean onKeyUp (int keycode,keyevent event) {
if (keycode = = Keyevent.keycode_dpad_down) {
Mysurfaceview.y + = 20;
}else if (keycode = = keyevent.keycode_dpad_up) {
MYSURFACEVIEW.Y-= 20;
}else if (keycode = = Keyevent.keycode_dpad_left) {
mysurfaceview.x-= 20;
}else if (keycode = = keyevent.keycode_dpad_right) {
mysurfaceview.x + = 20;
}
Return Super.onkeyup (KeyCode, event);
}

public boolean ontouchevent (Motionevent event) {
mysurfaceview.x = Event.getx ();
MYSURFACEVIEW.Y = Event.gety ();

Return Super.ontouchevent (event);
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}

}

View class and Surfaceview detailed description

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.