Use SurfaceView and Canvas in Android to draw animations

Source: Internet
Author: User

Use SurfaceView and Canvas in Android to draw animations

In fact, each View has a Canvas that can be used to draw an animation. You only need to reload the onDraw () method in this View, but the SurfaceView class is a class dedicated to brake animation.


Canvas is similar to the canvas label in HTML5. Canvas + SurfaceView makes animations more effective than View animations and Property animations.Suitable for a large number of centralized playback animationsSuch as game images and Image Display of cameras.


Because SurfaceView usuallyAnother dedicated threadThe UI is constantly re-painted, so unlike other animations, playing an animation in the main thread (UI thread) consumes a certain level of smoothness to respond to user input.


Note the following points when using SurfaceView:

1)Each SurfaceView requiresSurfaceHolderTo process the life cycle of this SurfaceView and obtain the Canvas object of this SurfaceView. You can call the getHolder () method of SurfaceView to obtain its SurfaceHolder object.


2)SurfaceView is generally implemented by inheriting SurfaceView. You can use the implements interfaces Runnable and SurfaceHolder. Callback. The second interface needs to overload three functions. These three functions are the life cycle processing of SurfaceView. You can pass the implemented Callback object through the addCallback () method of the SurfaceHolder object.


3)When using the SurfaceView Canvas, remember to lock the synchronization, because the Canvas cannot draw multiple patterns at the same time, by calling the SurfaceView SurfaceHolder objectLockCanvas ()This can be done. When the SurfaceHolder object is calledUnlockCanvasAndPost ()Method to unlock and update.


The following is an example of using SurfaceView and Canvas to draw an animation. Generally, you can directly copy it and run it 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 and will continue to move along the square route */class GameObject {private float x; private float y; private Bitmap img; private 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. drawBitmap (Img, x, y, paint);} // obtain the position of the object to be drawn next time (the object is continuously moving along a square with a side length of 400) public void getNextPos () {if (y = 100 & x! = 500) x + = 5; else if (x = 500 & y! = 500) y + = 5; else if (y = 500 & x! = 100) x-= 5; else if (x = 100 & y! = 100) y-= 5 ;}}/** this class is the class after SurfaceView is processed, all objects to be moved are finally drawn here */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 (); // lock the canvas and obtain the canvas of the SurfaceView. drawColor (Color. BLACK); obj. drawSelf (canvas); // pass the SurfaceView canvas to the object. The object will use this canvas to draw itself to a position above this. surfaceHolder. unlockCanvasAndPost (canvas); // release the lock and submit the canvas for repainting try {Thread. sleep (10); // This is equivalent to the frame rate. The smaller the value, the smoother the image.} 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) {// The part triggered when SurfaceView changes} @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (new MySurfaceView (getApplicationContext (); // load the processed SurfaceView at the beginning} @ Overridepublic boolean onCreateOptionsMenu (Menu menu Menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}


If reprinted please indicate 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.