Android game development-notes sorting-surfaceview game framework sorting

Source: Internet
Author: User

I have been reading android game programming from scratch recently,ArticleI wrote well. I felt that the author told me about the knowledge and problems I learned, and I learned a lot after reading it. In this article, I will take a note of the fifth chapter-game development practices to learn and consolidate the overall process of game development.

I. The surfaceview game framework is used.

Surfaceview is more suitable for game development because the canvas and double buffering mechanism are updated on a regular basis in the game.

1. First, review the surfaceview game development framework

Public calss mysurfaceview () extends surfaceview implements callback, runnable {

Private sufaceholder SFH; // used to control the surfaceview size and format, and listen to the surfaceview status. Surfaceview only saves the pixel data of the current view,

// We will not deal with surfaceview. They are controlled by surfaceholder and obtained by using the lockcanvas () function of surfaceholder.

// The canvas object on surfaceview, and then modify the data in surfaceview by drawing the content on the canvas. In general, it is an indirect form.

Private paint;

Private thread th; // because canvas update and screen refreshing are involved, you must use a separate thread to update the canvas. This will not cause the main UI thread to be updated because the screen update takes too long.

// The function is blocked by the rendering function, causing failure to respond to buttons, touch screens, and other operations. As an example of text moving with your fingers, when you remove the thread, the text will continue to change without clicking the screen.

Private Boolean flag; // specifies the thread flag, which is used to destroy a thread. In addition, it also prevents repeated thread creation andProgramAbnormal Functions

Private canvas;

Private int screenw, screenh;

Public mysurfaceview (context) // mainly responsible for loading views

{

Create a surfaceholder instance, add listeners for surfaceholder, instantiate paint brushes, set colors, set focus, load images, initialize game interfaces, and so on.

}

@ Override

Public void surfacecreated (surfaceholder holder)

{

Screenw = This. getwidth (); // the height and width of the view can only be obtained in the function of creating a view.

Screenh = This. getheight ();

Flag = true;

Th = new thread (this); // to avoid the increase in the number of threads and exceptions when the back and home keys are pressed,

// Put the thread creation and startup in the view creation function, and the flag = false in the view destruction function.

Th. Start ();

}

// Customize the plotting function

Public void mydraw ()

{

Try {// here try-catch-finally exception handling is used because when surfaceview is not editable or has not been created, the lockcanvas () function is called and null is returned,

// If null is returned, an error will occur if you plot the canvas.

Canvas = SFH. lockcanvas (); // get the canvas

If (canvas! = NULL)

{

Screen swiping and drawing

}

} Catch (exception e ){}

Finally {

If (canvas! = NULL) // if an error occurs before the canvas is submitted, unlocking and submitting the canvas function cannot be executed, an exception will be thrown the next time you obtain the canvas through locakcanvas.

// Put it in finally to unlock and submit the canvas

SFH. unlockcanvasandpost (canvas );

}

}

Public void logic () {// game logicCode}

@ Override

Public void run () {// The canvas is updated from time to time by the thread and the status of game elements

While (FLAG ){

Long start = system. currenttimemils ();

Mydraw ();

Logic ();

Long end = system. currenttimemils ();

Try {

} Catch (interruptedexception e) {e. printstacktrace ()}

}

There are also buttons, touch screen monitoring and other functions.

}

 

I saw a good article on surfaceview Analysis in the blog Park. I cut some of the articles and learned from them.

Address: http://www.cnblogs.com/xuling/archive/2011/06/06/android.html

 

First, let's take a look at the introduction of surfaceview by the official API.

Introduction to surfaceview APIs

Provides a dedicated drawing surface embedded inside of a view hierarchy. you can control the format of this surface and, if you like, its size; the surfaceview takes care of placing the surface at the correct location on the screen

The surface is Z ordered so that it is behind the window holding its surfaceview; The surfaceview punches a hole in its window to allow its surface to be displayed. the view hierarchy will take care of correctly compositing with the surface any siblings of the surfaceview that wowould normally appear on top of it. this can be used to place overlays such as buttons on top of the surface, though note however that it can have an impact on performance since a full alpha-blended composite will be written med each time the surface changes.

Access to the underlying surface is provided via the surfaceholder interface, which can be retrieved by calling getholder ().

The surface will be created for you while the surfaceview's window is visible; You shocould implement surfacecreated (surfaceholder) and surfacedestroyed (surfaceholder) to discover when the surface is created and destroyed as the window is shown and hidden.

One of the purposes of this class is to provide a surface in which a secondary thread can render in to the screen. if you are going to use it this way, you need to be aware of some threading semantics:

• All surfaceview and surfaceholder. callback methods will be called from the thread running the surfaceview's window (typically the main thread of the application ). they thus need to correctly synchronize with any State that is also touched by the drawing thread.
• You must ensure that the drawing thread only touches the underlying surface while it is valid -- between surfaceholder. Callback. surfacecreated () and surfaceholder. Callback. surfacedestroyed ().
Corresponding Chinese Translation
Surfaceview is an inherited class of view, which is embedded with a surface dedicated for painting. You can control the format and size of the surface. Surfaceview controls the position of this surface.
Surface is ordered in depth (Z-ordered), which indicates that it is always behind its own window. Surfaceview provides a visible area where only the surface content in the visible area is visible and the area outside the visible area is invisible. The layout display of the surface is affected by the hierarchical view relationship, and its sibling view node is displayed at the top. This means that the content of the surface is blocked by its sibling view, which can be used to place overlays (for example, controls such as text and buttons ). Note: if there is a transparent control on the surface, every change to it will cause the framework to recalculate its transparency and the top-level control, which will affect the performance.
You can access this surface through the surfaceholder interface. The getholder () method can obtain this interface.
When surfaceview becomes visible, the surface is created. Before surfaceview is hidden, the surface is destroyed. This saves resources. If you want to check the time when the surface is created and destroyed, you can reload surfacecreated (surfaceholder) and surfacedestroyed (surfaceholder ).
The core of surfaceview is to provide two threads: the UI thread and the rendering thread. Note:
1> All surfaceview and surfaceholder. Callback methods should be called in the UI thread, which is generally the main thread of the application. Various variables accessed by the rendering thread should be processed synchronously.
2> because the surface may be destroyed, it is only in surfaceholder. callback. surfacecreated () and surfaceholder. callback. surfacedestroyed () is valid, so make sure that the rendering thread accesses a valid surface.

 

Next, let's talk about our understanding of it.
1. Definition

Image data can be obtained directly from hardware interfaces such as memory or DMA, which is a very important drawing container.

Its feature is that it can be drawn to the screen outside the main thread. In this way, the main thread blocking can be avoided when the drawing task is heavy, thus improving the response speed of the program. Surfaceview is often used in game development. The background, characters, and animations in the game should be drawn in the canvas whenever possible.

2. Implementation

First, we inherit surfaceview and implement the surfaceholder. Callback interface.
The reason for using the interface: Because surfaceview has a principle, all the drawing work must be created after the surface (surface-surface, this concept is often mentioned in graphic programming. Basically, we can use it as a ing of the display to write the content to the surface.
Can be directly copied to the video memory for display, which makes the display speed very fast), and must end before the surface is destroyed. Therefore, surfacecreated and surfacedestroyed in callback form the boundary of the drawing processing code.

Method to be rewritten

(1) Public void surfacechanged (surfaceholder holder, int format, int width, int height ){}

// Triggered when the surface size changes

(2) Public void surfacecreated (surfaceholder holder ){}

// Triggered during creation. Generally, the drawing thread is called here.

(3) Public void surfacedestroyed (surfaceholder holder ){}

// Triggered when the image is destroyed. Generally, the painting thread is stopped and released here.

The whole process: inherits surfaceview and implements surfaceholder. callback interface ----> surfaceview. getholder () obtains the surfaceholder object ----> surfaceholder. addcallback (callback) adds the callback function ----> surfaceholder. lockcanvas () Get the canvas object and lock the canvas ----> canvas painting ----> surfaceholder. unlockcanvasandpost (canvas) ends the lock drawing, and submits changes to display the drawing.

3. surfaceholder
Surfaceholder is used as a surface controller to manipulate the surface. It processes effects and animations drawn on its canvas, controls the surface, size, pixels, and so on.
Several Methods to note:
(1) Abstract void addcallback (surfaceholder. Callback callback );
// Send a callback object to the current owner of surfaceview.
(2) Abstract canvas lockcanvas ();
// Lock the canvas. After locking the canvas, you can use its returned canvas object to draw a picture on it.
(3) Abstract canvas lockcanvas (rect dirty );
// Draw a picture in a certain area of the canvas. After the painting, the unlockcanvasandpost file is called to change the display content.
// For games with relatively high memory requirements, you do not need to redraw pixels in other regions outside dirty to increase the speed.
(4) Abstract void unlockcanvasandpost (canvas );
// Stop the locked drawing and submit the changes.

 

 

 

 

 

 

 

Related Article

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.