Surfaceview for Android Development

Source: Internet
Author: User

 

Surfaceview for Android Development

/*

* Surfaceview for Android Development

* Beijing Android Club group: 167839253

* Created on: 2011-8-26

* Author: blueeagle

* Email: liujiaxiang@gmail.com

*/

 

Surfaceview is used for video playback and simple camera preparation. So what does this class do? If this class is not used, can the View class be used? This does not seem to work.

Surfaceview will be used for games or video-related development. For surfaceview, first you need to know its location:

Extends
View

Java. Lang. Object

Bytes

Android. View. View

 

Bytes

Android. View. surfaceview

It can be seen from the manual:

Surfaceview is an inherited class of the View class. This view is embedded with a surface dedicated for drawing. This can be understood similarly as a canvas in the view. You can control the format and size of the surface. The surfaceview class controls the correct position of the surface on the screen.

Android advanced programming:

In general, the view of an application is drawn in the same GUI thread. This main application thread is also used to process all user interactions (such as Button clicking or text input ).

The ondraw () method of a view cannot be used to move it to the background thread. Because modifying a GUI element from the background thread will be explicitly forbidden.

When you need to quickly update the view ui or the current rendering code blocks the GUI thread for a long time, surfaceview is the best solution to the above problem. Surfaceview encapsulates a surface object instead of a canvas. This is important because the surface can be drawn using background threads. This is especially useful for Resource-sensitive operations, or for areas requiring fast updates or high frame rates, such as using 3D graphics, creating games, or previewing cameras in real time.

1. When should surfaceview be used?

Surfaceview uses the same method as any class derived from view. You can apply animations like other views and place them in the layout.

Surfaceview encapsulates the surface to support all standard canvas methods for plotting, and also supports a full OpenGL ES library.

With OpenGL, you can draw any 2D or 3D objects on the surface. This method relies on hardware acceleration (when available) compared to simulating the same effect on the 2D canvas) to greatly improve the performance.

Surface is particularly useful for displaying dynamic 3D images, such as applications using Google Earth or interactive games that provide immersive experiences. It is also the best choice for real-time camera preview.

2. Create a New surfaceview Control

To create a new surfaceview control, you must create a new class that extends surfaceview and implement surfaceholder. callback.

The surfaceholder callback can notify the view when the underlying surface is created and destroyed, and pass it to the reference of the surfaceholder object, which includes the currently valid surface.

A typical surfaceview design model includes a class derived from thread, which can receive references to the current surfaceholder and update it independently.

3. Use surfaceview to create a 3D control

Android fully supports the OpenGL ES 3D rendering framework, including hardware acceleration for devices. The surfaceview control provides a surface for rendering your OpenGL scenario on it.

We can use this method when using it:

Passively update the image. For example, you can use view for chess. Because image update relies on ontouch for update, you can use invalidate directly. In this case, this touch and the next touch take a longer time and will not be affected.

Actively update. For example, a person is always running. This requires a separate thread to repeatedly repaint the state of the person, to avoid blocking the main UI thread. Obviously, the view is not suitable and needs surfaceview for control.

 

Image data can be obtained directly from memory or hardware devices such as cameras, 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.

How to use a surfaceview:

First, it inherits surfaceview and implements the surfaceholder. Callback interface. Because there is a principle to use surfaceview, all the drawing work must start after the surface is created. It 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.

About 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.

The test code is as follows:

/** Surfaceview * surfaceview01.java * created on: 2011-8-25 * Author: blueeagle * Email: liujiaxiang@gmail.com */package COM. blueeagle; import android. app. activity; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. graphics. rect; import android. OS. bundle; import android. view. surfaceholder; import Ndroid. view. surfaceview; public class surfaceview01 extends activity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (New myview (this);} // class inside the view myview extends surfaceview implements surfaceholder. callback {private surfaceholder holder; private mythread; Public myview (Context) {super (context); // todo auto-generated constructor stub holder = This. getholder (); holder. addcallback (this); mythread = new mythread (holder); // create a drawing thread} @ override public void surfacechanged (surfaceholder holder, int format, int width, int height) {// todo auto-generated method stub} @ override public void surfacecreated (surfaceholder holder) {// todo auto-generated method St UB mythread. isrun = true; mythread. start () ;}@ override public void surfacedestroyed (surfaceholder holder) {// todo auto-generated method stub mythread. isrun = false ;}}// Internal Thread 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 the canvas. After locking the canvas, you can use the canvas object it returns to draw a picture on it. C. drawcolor (color. black); // set the canvas background color paint P = new paint (); // create a paint brush p. setcolor (color. white); rect r = new rect (100, 50,300,250); C. drawrect (R, P); C. drawtext ("this is the" + (count ++) + "seconds", 100,310, P); thread. sleep (1000); // The sleep time is 1 second} catch (exception e) {// todo: handle exception E. printstacktrace ();} finally {If (C! = NULL) {holder. unlockcanvasandpost (c); // end the lock drawing and submit the changes. }}}}}}

 

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.