Android learning 3. surfaceview Learning

Source: Internet
Author: User

To learn surfaceview, you must understand surfaceview, surface, and surfaceholder.

1. Surface

The following is an overview of the surface API provided by Google:

Handle onto a raw buffer that is being managed by the screen compositor.

Read data directly from the raw buffer to the screen.

Surface refers to the interface, which can be understood as the screen we want to display. However, knowledge is first stored in the memory, and then displayed on the screen, that is, surfaceview.

Several important methods

Ii. surfaceholder

The following is an overview of surfaceholder APIs provided by Google:

Abstract interface to someone holding a display surface. allows you to control the surface size and format, edit the pixels in the surface, and monitor changes to the surface. This interface is typically available throughSurfaceView
Class.

When using this interface from a thread other than the one running itsSurfaceView, You will want to carefully read the methodslockCanvas()AndCallback.surfaceCreated().

Surfaceholder is an abstract interface used to display a surface. It allows you to control the surface size and format, allow you to edit the surface, and monitor the surface changes. This interface

Typical applications are implemented through the surfaceview class.

When you use this interface in a thread instead of running a surfaceview, You need to master the lockcanvas () andCallback.surfaceCreated().

Surfaceholder is the interface used to operate the surface.

Surfaceholder Method

Parameters of the settype () method of surfaceholder:

Surface_type_normal: Use Ram to cache the normal surface of native data
Surface_type_hardware: Applicable to the DMA (Direct Memory Access) engine and hardware-accelerated Surface
Surface_type_gpu: GPU-accelerated Surface
Surface_type_push_buffers: indicates that the surface does not contain native data. The surface data is provided by other objects. This type of surface is used in the camera image preview, and camera is responsible for previewing the surface data, in this way, the image preview will be smoother. If this type is set, you cannot call lockcanvas to obtain the canvas object.

Although the settype () method has been declared deprecated, it is better to set it when necessary.

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.

3. surfaceview

The following is an overview of surfaceview APIs provided by Google:

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 placed med each
Time the surface changes.

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

The surface will be created for you while the surfaceview's window is visible; You shoshould implementsurfaceCreated(SurfaceHolder)AndsurfaceDestroyed(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 into the screen. if you are going to use it this way, you need to be aware of some threading semantics:

  • All surfaceview andSurfaceHolder.CallbackMethods 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 --SurfaceHolder.Callback.surfaceCreated()AndSurfaceHolder.Callback.surfaceDestroyed().

Copy someone else's translation (alas, English is too bad to hurt !, Learning English !)

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.

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) stops locking the drawing and submits changes to display the drawing.

The following is a simple test of surfaceview. It is recommended that you set surfaceholder. addcallback, override the method in it, and draw a picture in surfaceview in public void surfacecreated (surfaceholder holder) to prevent the surfaceview from being created.

Import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. graphics. rect; import android. OS. bundle; import android. util. log; import android. view. surfaceholder; import android. view. surfaceview;/*** draw a screen-filled grid **/public class surfaceviewtest2activity extends activity {/** called When the activity is first created. */private surfaceview; private surfaceholder holder; private int screenwidth; private int screenheight; private timer; private mytimertask1 task1; private float currentx = 0.0f; // record the progress of the current horizontal draw line Private float currenty = 0.0f; // record the progress of the current vertical draw line Private paint; // brush private Boolean reversion = false; // controls the number of rows to be drawn. Private int countline = 0; // records the number of rows to be drawn. Line @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // calculate the screen width and height screenwidth = getwindowmanager (). getdefadisplay display (). getwidth (); screenheight = getwindowmanager (). getdefadisplay display (). getheight (); // surfaceview and holder initialization surfaceview = (surfaceview) findviewbyid (R. id. SV); holder = surfaceview. getholder (); holder. addcallback (New surfa Cecallback (); // timer and task initialization timer = new timer (); task1 = new mytimertask1 (); // set paint to new paint (); paint. setcolor (color. green); // the paint brush is green... paint. setstrokewidth (2); // set the paint width} public class surfacecallback implements surfaceholder. callback {public void surfacecreated (surfaceholder holder) {timer. schedule (task1, 1000, 5);} public void surfacechanged (surfaceholder holder, int format, int width, int heig HT) {} public void surfacedestroyed (surfaceholder holder) {}} class mytimertask1 extends timertask {@ overridepublic void run () {// start drawing drawgrid (currentx, currenty ); // if it is not reversed, currentx ++ and if (! Reversion) currentx ++; elsecurityx --; // You can synchronize the X and Y records. However, I don't know why, on the simulator, X is at the top, Y does not have // but from the output, it is synchronous, probably because of the problem on the simulator currenty = (float) screenheight/screenwidth) * currentx; log. I ("test", currentx + "" + currenty); // If the screen is exceeded, the line is reversed, and the number of lines must be 1if (currentx> = screenwidth) {reversion = true; countline ++;} If (currentx <= 0) {reversion = false; countline ++ ;}} public void drawgrid (float X, float y) {canvas = hol Der. lockcanvas (New rect (0, 0, screenwidth, screenheight); If (! Reversion) {// No reverse painting canvas. drawline (0, countline * 15, X, countline * 15, paint); canvas. drawline (countline * 15, 0, countline * 15, Y, paint);} else {// reverse drawing canvas. drawline (screenwidth, countline * 15, X, countline * 15, paint); canvas. drawline (countline * 15, screenheight, countline * 15, Y, paint);} holder. unlockcanvasandpost (canvas );}}

Refer to the Learning Article: Click to open the link

Refer to the Learning Article: Click to open the link

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.