Use Surfaceview and canvas to draw animations in Android

Source: Internet
Author: User

In fact, each view has a canvas can be used to draw animation, only need to overload the OnDraw () method in this view can be, but the Surfaceview class is a dedicated to brake animation class.


Canvas (called "canvas" in Chinese) is the same as the canvas label in HTML5, which allows you to freely draw graphics within a certain area. Canvas+surfaceview animation is more suitable for a large number of centrally played animations than the View animation and property animation animations, such as game screen, camera image display, etc.


Because Surfaceview often redraws the interface in another dedicated thread , it does not play the animation in the main thread (the UI thread) as well as other animations and consumes some smoothness in response to user input.


Here are some points to note when using Surfaceview:

1) Each surfaceview requires a surfaceholder object to handle this Surfaceview life cycle and get the Surfaceview canvas object. You can get its Surfaceholder object by calling Surfaceview's Getholder () method.


2) The use of Surfaceview is generally achieved by inheriting the Surfaceview way, you can implements two interfaces, runnable and Surfaceholder.callback, respectively. The second interface needs to overload three functions, these three functions are surfaceview life cycle processing, you can pass the Surfaceholder object's Addcallback () method to achieve good callback object.


3) Be sure to remember to lock sync when using Surfaceview canvas, because you can't have the canvas draw multiple patterns at the same time by calling the Lockcanvas of this Surfaceview Surfaceholder object () can do that. Once drawn , the Unlockcanvasandpost () method of calling the Surfaceholder object can be unlocked and updated.


Here is an example of animating with Surfaceview and canvas, which can be run on a direct copy to see the effect:

Package Com.example.canvastest;import Android.app.activity;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.os.bundle;import Android.view.Menu;import Android.view.surfaceholder;import Android.view.surfaceview;import Android.widget.toast;public class MainActivity Extends Activity {/* * This class is used as a test object that will continue to move along a square route */class gameobject {private float x;private float y;private Bitmap img;priv Ate Paint paint;public gameobject () {this.img = Bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher); this.x = 100;this.y = 100;this.paint = new paint ();} Draw your own public void drawself (canvas canvas) {Canvas.drawbitmap (img, x, y, paint) on your canvas after Surfaceview and lock sync;} Gets the position of the next object to be drawn (this is the constant movement of a square along a side length of 400) public void Getnextpos () {if (y = = && x! =) x + = 5;else if (x = = 50 0 && Y! = x) y + = 5;else if (y = = && X! =) x-= 5;else if (x = = && Y! =) Y-= 5;}} /* * This class is the class after processing the Surfaceview, all the objects to be moving are finally placed here to draw */class Mysurfaceview extends Surfaceview implements Surfaceholder.callback, Runnable {private thread thread;//Surfaceview usually requires a separate thread to play the animation private Canvas canvas;private Surfaceholder surfaceholder;private gameobject obj;public mysurfaceview (Context c) {super (c); This.surfaceholder = This.getholder (); This.surfaceHolder.addCallback (this); this.obj = new Gameobject ();} @Overridepublic void Run () {while (true) {obj.getnextpos (); canvas = This.surfaceHolder.lockCanvas ();// By Lockcanvas Lock and get the Surfaceview canvas Canvas.drawcolor (color.black); obj.drawself (canvas); Pass the Surfaceview canvas to the object, and the object will draw itself to a position above it with this canvas this.surfaceHolder.unlockCanvasAndPost (canvas); Release the lock and submit the canvas to redraw try {thread.sleep (10);//This is equivalent to the frame rate, the smaller the value of the picture is smoother} catch (Exception e) {e.printstacktrace ();}}} @Overridepublic void surfacedestroyed (Surfaceholder arg0) {Toast.maketext (Getapplicationcontext (), "Surfaceview has been destroyed ", Toast.length_loNG). Show ();} @Overridepublic void surfacecreated (Surfaceholder arg0) {Toast.maketext (Getapplicationcontext (), "Surfaceview created", Toast.length_long). Show (); this.thread = new Thread (this); This.thread.start ();} @Overridepublic void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {//This is the part that fires when Surfaceview changes) @Ov errideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (new Mysurfaceview (Getapplicationcontext ())); Don't forget to start by loading our processed Surfaceview} @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; this adds it EMS to the Action Bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


If reproduced please specify the source: Http://blog.csdn.net/gophers



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.