Android Surfaceview Learning

Source: Internet
Author: User

Recent projects have encountered a problem that requires real-time display of hand coordinates on the screen, which involves a real-time drawing problem. For the real-time updating of the UI this problem, know that Android's UI updates need to be updated in the main thread, but if you put a real-time drawing operation on the main thread, there must be a problem blocking the main thread, even if it does not block the main thread, it will reduce the speed of the program to run. So I was thinking of a control of Android, Surfaceview. This control is described on the official website as follows:

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 valid between SurfaceHolder.Callback.surfaceCreated () and SurfaceHolder.Callback.surfaceDestroyed (), So make sure that the rendering thread is accessing the legitimate, effective surface.

With this passage, we can see that Surfaceview provides the UI thread. You can update the UI yourself, so that we can do real-time painting in Surfaceview, and then change the drawing data in it to achieve the real-time update UI we want, and consume smaller resources. Then let's talk about the implementation of the problem in detail.

So how do we use Surfaceview to achieve our needs? First we need to customize a control and inherit the Surfaceview class. And the interface in which the surfaceholder.callback is to be implemented. The interface is implemented because we want to make sure that the operations we do need to be created before the Surfaceview can be started. Then let's take a look at the three functions that the function needs to implement.

New Surfaceholder.callback () {    @Override public    void surfacecreated (Surfaceholder surfaceholder) {// Action to be taken when creating    }    @Override public    void surfacechanged (surfaceholder surfaceholder, int i, int i1, int i2) {//s Urfaceview action to take when size changes    }    @Override public    void surfacedestroyed (Surfaceholder surfaceholder) {// The operation to be performed when destroying.    }}

Then if we want to draw the content and update it in real time, we need to open a thread in surfacecreated and draw it in real time. This is what we need to accomplish. But there is a need for some attention when drawing. This after the next presentation of the code we come to specific analysis and concrete look, followed by the custom view of the specific code. Let's take a concrete look.

public class MyView extends Surfaceview {private final String TAG = "Acmtest";    Private Surfaceholder Msurfaceholder;    Private Canvas mcanvas;//Canvas public boolean isrunning;//is used to identify whether to open a drawing thread.    Context context;        int positionx;//The x-coordinate of the drawing, int positiony;//the y-coordinate of the drawn graphic, public MyView (context context) {super (context);    Init ();        } public MyView (context context, AttributeSet AttributeSet) {super (Context,attributeset);        This.context = context;    Init (); }//Initialize Surfaceview, in this function, implement Surfaceholder.callback public void init () {SetBackgroundColor (Color.parsecolor ("#6A14 B7f5 "));//sets the background color of Surfaceview setzorderontop (TRUE);//causes Surfaceview to be placed at the top level Getholder (). SetFormat ( pixelformat.translucent);//enable the window to support transparency Msurfaceholder = Getholder (); Msurfaceholder.addcallback (New Surfaceholder.callback () {@Override public void surfacecreated (Surfaceholder                Surfaceholder) {//start the thread that started painting, the function in this thread does not need to be executed in the main threads, can execute and update the UI directly. New Thread (New Runnable () {@Override public void run () {while (isrunning)                        {Drawpoint ();            }}). Start ();            } @Override public void surfacechanged (Surfaceholder surfaceholder, int i, int i1, int i2) {    } @Override public void surfacedestroyed (Surfaceholder surfaceholder) {}});        }//The operation of the concrete painting public void Drawpoint () {//need to be aware that this is the way to get the canvas and not be able to assert itself, in order to guarantee a canvas from start to finish.        Mcanvas = Msurfaceholder.lockcanvas (); if (Mcanvas! = null) {try {mcanvas.drawcolor (color.transparent, PorterDuff.Mode.CLEAR);//is to clean up the last The content of the painting, this is based on the need to choose whether to add.                Because my requirement is to track the location, if not added, the last picture will be retained. Paint paint = new paint ();//Declaration brush, based on which to draw Paint.setcolor (color.red);//For Red Brush MCANVAS.DRAWCIR CLE (Positionx,positIony,10,paint);            } catch (Exception e) {e.printstacktrace (); } finally {msurfaceholder.unlockcanvasandpost (Mcanvas);//The submitted canvas will be updated after submission and then displayed}}} p        ublic void setposition (int positionx,int positiony) {This.positionx = Positionx;    This.positiony = Positiony; }}

  

This is done by inheriting Surfaceview to implement a real-time update UI and then consuming a small amount of memory. It is worth noting that when initializing, we need to consider the first three lines of init code, set the background color, do not set in XML, need to set in this, otherwise the default background is pure black. Then the last two sentences are supported for transparent colors, and remain able to be at the top of the layout.

One more thing is to get the canvas. This requires strict compliance, first fetch, and then submit the update, where it cannot be re-declared, and the need for submission and acquisition is the same canvas.

  

Android Surfaceview Learning

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.