Android在SurfaceView做动画一般方法

MainActivity

1 package com.example.surfacemove; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 7 public class MainActivity extends Activity { 8 9@Override 10public void onCreate(Bundle savedInstanceState) { 11super.onCreate(savedInstanceState); 12setContentView(new MyView(this)); //指定界面 13} 14 15@Override 16public boolean onCreateOptionsMenu(Menu menu) { 17getMenuInflater().inflate(R.menu.activity_main, menu); 18return true; 19} 20 21 22 }

MyView
1 package com.example.surfacemove; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.Paint; 7 import android.graphics.Paint.Style; 8 import android.view.SurfaceHolder; 9 import android.view.SurfaceHolder.Callback; 10 import android.view.SurfaceView; 11 12 public class MyView extends SurfaceView implements Runnable, Callback { 13 14private Paint paint; 15private Canvas canvas; 16private boolean isRunning = true; //标志新线程是否运行 17private SurfaceHolder sh; 18private int i; 19 20public MyView(Context context) { 21super(context); 22paint = new Paint(); 23paint.setStyle(Style.STROKE); 24paint.setColor(Color.GREEN); 25paint.setAntiAlias(true); 26sh = getHolder(); //得到surfaceholder 27sh.addCallback(this); //添加回调 28} 29 30public void surfaceChanged(SurfaceHolder holder, int format, int width, 31int height) {//界面改变时调用 32 33} 34 35public void surfaceCreated(SurfaceHolder holder) {//界面创建后调用 36new Thread(this).start(); //开启新线程 37} 38 39public void surfaceDestroyed(SurfaceHolder holder) {//界面销毁后调用 40isRunning = false; //标志位置为假 41} 42 43public void run() {//run函数 44while (isRunning) {//如果标志位为真 45i++; 46if(i==50){ 47i=0; 48} 49drawView(); //画画面 50try { 51Thread.sleep(100); //延时 52} catch (InterruptedException e) { 53e.printStackTrace(); 54} 55} 56} 57 58private void drawView() {//画画函数 59try { 60if(sh!=null){//若sh不为空 61canvas = sh.lockCanvas(); //得到canvas 62canvas.drawColor(Color.BLACK); //清屏 63canvas.drawCircle(100, 100, i, paint); 64} 65} catch (Exception e) { 66e.printStackTrace(); 67}finally{ 68if(canvas!=null){//若canvas不为空 69sh.unlockCanvasAndPost(canvas); //解锁canvas 70} 71} 72} 73 }

【Android在SurfaceView做动画一般方法】
转载于:https://www.cnblogs.com/hzy3774/archive/2012/07/13/2590946.html

    推荐阅读