Android game development (I) simple graphic rendering

Source: Internet
Author: User

Android game development generally uses the view or surfaceView chapter to learn how to use the view or surfaceView.
 
Let's first look at the View
The view class is a superclass of android. This class contains all screen types. Each View has a canvas for drawing, which can be expanded at will. any view class only needs to override the onDrae () method to display the interface.
The core of the game is to constantly draw and refresh the interface. We use the onDraw method to draw images. How can we refresh the interface? The ivalidate method is provided in android to refresh the interface, note that invalidate cannot be called directly in the thread (that is, it cannot be called again in the Child thread) because it violates the android single-thread model, android ui operations are not thread-safe and must be executed in the ui thread. The most common method in normal use is to update the ui thread through handler.
Next let's take a look at the effect of moving an image up or down.
This example has two classes
A gameView class inherits the View class as the game interface output and control class.
The MainActivity class needs to inherit the Activity as the program entry and refresh our view.
Let's first look at the content of the gameView class.
 
Package yxqz.com;
 
Import android. content. Context;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. graphics. Canvas;
Import android. util. DisplayMetrics;
Import android. util. Log;
Import android. view. View;
 
/**
* For a simple android view image, this class must inherit the view base class.
* @ Author mahaile
*
*/
Public class GameView extends View {
Bitmap bitmap_role;
Float width, height;
Float x, y; // The Position of the screen where the image is rendered
Int direction = 0; // The image running direction controls the Image Moving up or down
/**
* Constructor
* @ Param context
* @ Param width: screen width
* @ Param height screen height
*/
Public GameView (Context context, float width, float height ){
Super (context );
This. width = width;
This. height = height;
// The BitmapFactory. decodeResource method can automatically load the image R. drawable. role parameter in the res/drawable directory to the image id automatically generated by android.
Bitmap_role = BitmapFactory. decodeResource (context. getResources (), R. drawable. role );
X = width/2-bitmap_role.getWidth ()/2;
}
 
@ Override
Protected void onDraw (Canvas canvas ){
// TODO Auto-generated method stub
Log. d ("GameView", "GameView onDraw x is:" + x + "y is:" + y); // Log class method for Log output
Canvas. drawBitmap (bitmap_role, x, y, null );
Super. onDraw (canvas );
}
}
 
Below is the MainActivity class
 
Package yxqz.com;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. util. DisplayMetrics;
Import android. util. Log;
 
Public class MainActivity extends Activity {
/** Called when the activity is first created .*/
GameView gameView;
GameSurfaceView gameSurfaceView;
 
Boolean flag; // stop refreshing the interface when the thread flag is set to false.
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );


// Obtain the screen width and height through displayMetrics
DisplayMetrics dm = new DisplayMetrics ();
This. getWindowManager (). getDefaultDisplay (). getMetrics (dm );
Int width = dm. widthPixels;
Int height = dm. heightPixels;
GameView = new GameView (this, width, height );
SetContentView (gameView );
Flag = true;
New Thread (new GameThread (). start ();
}

Class GameThread implements Runnable {
 
Public void run (){
While (flag ){
If (gameView. direction = 0 ){
GameView. y + = 0.2;
If (gameView. y> = gameView. height ){
GameView. direction = 1;
}
} Else {
GameView. y-= 0.2;
If (gameView. y <= 0 ){
GameView. direction = 0;
}
}
// Notify the UI thread to redraw. The main thread of gameView will automatically call the onDraw method.
GameView. postInvalidate ();

// If you use the gameView. invalidate (); method, you need to write gameView. invalidate () to handler because it only supports the use in the ui main thread}
}
}
}
}
 
 
The above example briefly explains how to use the android View. Next, let's look at how SurfaceView is used.
SurfaceView features: it can be drawn to the screen from a thread other than the main thread, which can avoid blocking the main thread when the drawing task is heavy, thus improving the response speed of the program.
Note that surfaceView does not have the OnDraw method and needs to be implemented and called again.
To use SurfaceView, you must first inherit SurfaceView and implement the SurfaceHolder. Callback interface.
To implement the SurfaceHolder. Callback interface, you need to implement the following interfaces:
 
// Called when the surface size changes, that is, when the screen is switched horizontally or vertically
Public void surfaceChanged (SurfaceHolder surfaceHolder, int format, int width, int height ){}
// Called when the surface is created. Generally, the screen rendering thread is started.
Public void surfaceCreated (SurfaceHolder surfaceHolder ){}
// This is called when the surface is destroyed. Generally, resource destruction and other operations are performed here.
Public void surfaceDestroyed (SurfaceHolder surfaceHolder ){}
 
SurfaceHolder is the surface controller used to control the surface. Process the effect, animation, surface control, size, pixel, and so on the Cavas.
Several methods need to be noted here
// Send a callback object to the current owner of SurfaceView.
(1) abstract void addCallback (SurfaceHolder. Callback callback );
// Lock the Canvas. Generally, you can return the Canvas object after the Canvas is locked and draw a picture on it.
(2) abstract Canvas lockCanvas ();
// Draw a picture in a certain area of the locked canvas, because after drawing, the unlockCanvasAndPost below will be called to change the displayed content for games with high memory requirements, you can increase the speed without re-painting pixels outside the rect area.
(3) abstract Canvas lockCanvas (Rect rect );
// Stop locking the canvas and submit changes
(4) abstract void unlockCanvasAndPost (Canvas canvas );
The whole process of using surfaceView
Inherit SurfaceView and implement SurfaceHolder. callback interface --> SurfaceView. getHolder () obtains the surfaceHolder object --> SurfaceHolder. addCallback (callback) adds a callback function --> SurfaceHolder. lockCanvas () Get the Canvas object and lock the Canvas -->
Canvas painting -->
SurfaceHolder. unlockCanvasAndPost (Canvas canvas) --> stop and lock the drawing and submit the changes.
 
The following shows the sample code GameSufaceView.
 
Package yxqz.com;

Import android. content. Context;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. graphics. Canvas;
Import android. graphics. Color;
Import android. view. SurfaceHolder;
Import android. view. SurfaceView;
Import android. view. SurfaceHolder. Callback;

/**
* Simple image rendering for android surfaceview
* @ Author mahaile
*
*/
Public class GameSurfaceView extends SurfaceView implements Callback {
 
Boolean flag; // stop refreshing the interface when the thread flag is set to false.
SurfaceHolder surfaceHolder;
GameViewThread gameViewThread;
Int x, y;
Int direction = 0; // The image running direction controls the Image Moving up or down
Int width, height;
Bitmap bitmap_role;
Public GameSurfaceView (Context context ){
Super (context );
SurfaceHolder = this. getHolder ();
SurfaceHolder. addCallback (this); // Add callback
Bitmap_role = BitmapFactory. decodeResource (getResources (), R. drawable. role );
}
 
Public void onDraw (Canvas canvas ){
Canvas. drawColor (Color. BLACK );
Canvas. drawBitmap (bitmap_role, width/2-bitmap_role.getWidth ()/2, y, null );
}

Public void surfaceChanged (SurfaceHolder surfaceHolder, int format, int width, int height ){

}

Public void surfaceCreated (SurfaceHolder surfaceHolder ){
// Obtain the width and height of the screen. It is valid only when the surface is created. It cannot be obtained in the constructor.
Width = this. getWidth ();
Height = this. getHeight ();
// Initialize the drawing thread
GameViewThread = new GameViewThread ();
GameViewThread. flag = true;
GameViewThread. start ();
}

Public void surfaceDestroyed (SurfaceHolder surfaceHolder ){
GameViewThread. flag = false; // destroy the thread
}

 
Class GameViewThread extends Thread {
Public boolean flag;
Public void run (){
While (flag ){
Canvas canvas = null;
Try {
If (direction = 0 ){
If (y> = height ){
Direction = 1;
}
Y + = 1;
} Else {
If (y <= 0 ){
Direction = 0;
}
Y-= 1;
}
Canvas = surfaceHolder. lockCanvas (); // lock the canvas and obtain the canvas
OnDraw (canvas); // call onDraw to render to the screen
SurfaceHolder. unlockCanvasAndPost (canvas); // do not forget this step. Otherwise, the page cannot be displayed.
} Catch (Exception e ){
E. printStackTrace ();
}

Try {
Thread. sleep (10); // The Thread sleep time unit is millisecond-controlled frames.
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} // Refresh every second


}
}
}
}

Let's take a look at the entry to the mainActicity code program. This is quite simple.

 
 
Package yxqz.com;

Import android. app. Activity;
Import android. OS. Bundle;
Import android. util. DisplayMetrics;
Import android. util. Log;

Public class MainActivity extends Activity {
/** Called when the activity is first created .*/
GameSurfaceView gameSurfaceView;

@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
GameSurfaceView = new GameSurfaceView (this );
SetContentView (gameSurfaceView );

}
 
}
 
The above lists view and surfaceView run two programs respectively. We found that the view in the above program is faster than the surfaceView's frame number. Why? Isn't surfaceView more efficient than view?
Do not think so. view is higher than surfaceView for rendering programs that are not complex. Another point is that no part of the above program consumes more cpu resources, surfaceView is more efficient than view if cpu consumption is high.
The following is the source code of the above program. If you are interested, you can study and welcome to shoot bricks.
Http://www.bkjia.com/uploadfile/2012/0417/20120417095628177.rar
 

 
From android, unity3d

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.