SurfaceView learning for Android (1)

Source: Internet
Author: User

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 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 canvas );
// Stop the locked drawing and submit the changes.
4. Instances
The example here implements a rectangle and a timer.
View Code
 
1 package xl. test;
2
3 import android. app. Activity;
4 import android. content. Context;
5 import android. graphics. Canvas;
6 import android. graphics. Color;
7 import android. graphics. Paint;
8 import android. graphics. Rect;
9 import android. OS. Bundle;
10 import android. view. SurfaceHolder;
11 import android. view. SurfaceView;
12
13 public class ViewTest extends Activity {
14/** Called when the activity is first created .*/
15 @ Override
16 public void onCreate (Bundle savedInstanceState ){
17 super. onCreate (savedInstanceState );
18 setContentView (new MyView (this ));
19}
20 // view internal class
21 class MyView extends SurfaceView implements SurfaceHolder. Callback
22 {
23 private SurfaceHolder holder;
24 private MyThread myThread;
25 public MyView (Context context ){
26 super (context );
27 // TODO Auto-generated constructor stub
28 holder = this. getHolder ();
29 holder. addCallback (this );
30 myThread = new MyThread (holder); // create a drawing thread
31}
32
33 @ Override
34 public void surfaceChanged (SurfaceHolder holder, int format, int width,
35 int height ){
36 // TODO Auto-generated method stub
37
38}
39
40 @ Override
41 public void surfaceCreated (SurfaceHolder holder ){
42 // TODO Auto-generated method stub
43 myThread. isRun = true;
44 myThread. start ();
45}
46
47 @ Override
48 public void surfaceDestroyed (SurfaceHolder holder ){
49 // TODO Auto-generated method stub
50 myThread. isRun = false;
51}
52
53}
54 // Internal Thread class
55 class MyThread extends Thread
56 {
57 private SurfaceHolder holder;
58 public boolean isRun;
59 public MyThread (SurfaceHolder holder)
60 {
61 this. holder = holder;
62 isRun = true;
63}
64 @ Override
65 public void run ()
66 {
67 int count = 0;
68 while (isRun)
69 {
70 Canvas c = null;
71 try
72 {
73 synchronized (holder)
74 {
75 c = holder. lockCanvas (); // lock the Canvas. After locking the Canvas, you can use its returned Canvas object to draw a picture on it.
76 c. drawColor (Color. BLACK); // you can specify the canvas background Color.
77 Paint p = new Paint (); // create a Paint brush
78 p. setColor (Color. WHITE );
79 Rect r = new Rect (100, 50,300,250 );
80 c. drawRect (r, p );
81 c. drawText ("this is the nth" + (count ++) + "second", 100,310, p );
82 Thread. sleep (1000); // The sleep duration is 1 second.
83}
84}
85 catch (Exception e ){
86 // TODO: handle exception
87 e. printStackTrace ();
88}
89 finally
90 {
91 if (c! = Null)
92 {
93 holder. unlockCanvasAndPost (c); // stop and lock the drawing and submit the changes.
94
95}
96}
97}
98}
99}
100}
 

 

From Juner's Blog

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.