Android Surfaceview (i)

Source: Internet
Author: User


First, let's take a look at the official API's introduction to Surfaceview.

Surfaceview's API Introduction

   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 in the screen

  the surface is Z ordered so it's behind the window holding its surfaceview; Surfaceview punches a hole in it window to allow it surface to be displayed. The view hierarchy'll take care of correctly compositing with the Surface any siblings of the surfaceview that would nor Mally appear on top of it. This can is used to place overlays such as buttons on top of the Surface, though note however that it can has an impact O n performance since a full alpha-blended composite'll be performed each time the Surface changes.

Access to the underlying surface was provided via the Surfaceholder interface, which can retrieved by calling Getholder ( ).

The Surface would be a created for your while the Surfaceview's window is visible; You should implement surfacecreated (Surfaceholder) and surfacedestroyed (Surfaceholder) to discover when the Surface is CRE Ated and destroyed as the window is shown and hidden.

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

  ? All Surfaceview and Surfaceholder.callback methods would be a called from the thread running the Surfaceview ' s window (typica Lly the main thread of the application). They thus need to correctly synchronize with any state that's also touched by the drawing thread.
  ? You must ensure so the drawing thread only touches the underlying Surface while it's valid--between surfaceholder.cal Lback.surfacecreated () and SurfaceHolder.Callback.surfaceDestroyed ().
the corresponding Chinese translation
Surfaceview is the inheritance class for view, which has a built-in surface for drawing. You can control the format and size of this surface. Surfaceview controls where this surface is drawn.
surface is a deep sort (z-ordered), which indicates that it is always behind its own window. The Surfaceview provides a visible area that is visible only on the surface portion of the visible area and not visible outside the visible area. The layout display of surface is affected by the view hierarchy, and its sibling view nodes are displayed at the top. This means that the content of surface is obscured by its sibling view, which can be used to place a cloak (overlays) (for example, text and buttons). Note that if you have transparent controls on your surface, each change will cause the framework to recalculate the transparency of its and top-level controls, which can affect performance.
you can get this interface by accessing the Surface,getholder () method through the Surfaceholder interface.
Surface is created when Surfaceview becomes visible, and surface is destroyed before Surfaceview is hidden. This will save resources. If you want to see when your surface is created and destroyed, you can reload surfacecreated (Surfaceholder) and surfacedestroyed (Surfaceholder).
the core of Surfaceview is the provision of two threads: the UI thread and the render thread. It should be noted here:
1> all methods of Surfaceview and Surfaceholder.callback should be called in the UI thread, which is generally the main thread of the application. The various variables to be accessed by the render thread should be processed synchronously.
2> because 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 legitimate, valid surface.

Next, talk about your 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.

It is characterized by the ability to draw on the screen in threads other than the main thread. This prevents the main thread from being blocked when the drawing task is heavy, which improves the program's response speed. In the game development more use Surfaceview, the game background, the character, the animation and so on as far as possible to draw in canvas canvases.

2. Realize

First inherit Surfaceview and implement Surfaceholder.callback interface
Reasons for using interfaces: because there is a principle of using Surfaceview, all the drawing work must be done before surface is created (surface-surface, which is often referred to in graphical programming.) Basically we can think of it as a mapping of video memory, to the content of surface
Can be copied directly to the video memory to display it, which makes the display very fast, and must end before surface is destroyed. So the surfacecreated and surfacedestroyed in callback are the boundaries of the drawing processing code.

Methods that need to be overridden

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

//Fires when the size of your surface changes

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

//Fires at creation time, typically called drawing threads here.

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

//Fires when destroyed, typically where the drawing thread is stopped and released.

The whole process: inherit Surfaceview and implement Surfaceholder.callback interface----> Surfaceview.getholder () Get Surfaceholder object----> Surfaceholder.addcallback (callback) Add callback function---->surfaceholder.lockcanvas () Get the canvas object and lock the canvas----> Canvas painting ---->surfaceholder.unlockcanvasandpost (canvas canvas) ends the lock drawing and submits the change to display the graphic.


3, Surfaceholder
Here's a class surfaceholder that you can use as a controller for your surface to manipulate your surface. Handle it on canvas to draw effects and animations, control surfaces, sizes, pixels, etc.
several methods to be aware of:
(1), abstract void Addcallback (Surfaceholder.callback Callback);
//Give Surfaceview the current holder a callback object.
(2), abstract Canvas Lockcanvas ();
//Lock the canvas, usually after it is locked, it can be drawn through canvas objects that it returns.
(3), abstract Canvas Lockcanvas (Rect dirty);
//Lock an area of the canvas for paint, etc... Since the drawing is finished, the following unlockcanvasandpost will be called to change the display.
//Relative part of the memory requirements of the relatively high game, you can not redraw the dirty outside the pixels of other areas, can improve speed.
(4), abstract void Unlockcanvasandpost (Canvas canvAS);
End the lock drawing and commit the change.

Code:

Create a new MyView class inheritance with Surfaceview used to draw the view:

<pre style= "font-family: Song body; font-size:12pt; Background-color:rgb (255, 255, 255);" ><span style= "color: #000080; Background-color: #e4e4ff;" ><strong></strong></span> 
Import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.rect;import Android.view.surfaceholder;import android.view.surfaceview;/** * View class * Created by Young on 2015/5/2.    */public class MyView extends Surfaceview implements surfaceholder.callback{private Surfaceholder holder;    Private MyThread MyThread;        Public MyView (Context context) {super (context);        Holder= This.gethandler (). Addcallback (this);        Holder = This.getholder ();//Get Holder Holder.addcallback (this);    Mythread=new MyThread (holder);//Create a drawing thread}//Fires at creation time, typically calling paint threads here.        @Override public void surfacecreated (Surfaceholder holder) {mythread.isrun=true;    Mythread.start ();    } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {} @Override   public void surfacedestroyed (Surfaceholder holder) {mythread.isrun=false; } class MyThread extends thread{private surfaceholder holder;        public Boolean Isrun;            Public MyThread (Surfaceholder holder) {this.holder=holder;        Isrun=true;            } @Override public void Run () {int count=0;                while (Isrun) {Canvas c=null; try {synchronized (holder) {C=holder.lockcanvas ();//Lock canvas, general                        After the lock is made, the canvas object that it returns can be used to paint, and so on. C.drawcolor (Color.White);//Set canvas background color paint paint=new paint ();//Create Brush Paint.set                        Color (color.yellow);//Brush color rect rect=new rect (100,50,300,250);                        C.drawrect (Rect,paint); Paint paint1=new paint ();//Create Brush Paint1.setcolor (color.black);//Brush Color PAINT1.S Ettextsize (20);//font Size C.drawtext ("This is the first" + (COunt++) + "SEC", paint1); Thread.Sleep (1000);//make Thread sleep 1s}} catch (Interruptedexception e) {E.P                Rintstacktrace (); } finally {if (c!=null) {holder.unlockcanvasandpost (c);//End Lock drawing,                    and submit changes. }                }            }        }    }}


Load the page created by MyView in Main_activity.java.

public class Mainactivity extends Actionbaractivity {    @Override    protected void OnCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (New MyView (this));       MyView myview=new MyView (this);}    }




Android Surfaceview (i)

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.