Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 SurfaceView 實作多執行緒動畫的完整示範

編輯:關於 Android 程式設計

做遊戲或高密度動畫時,普通的 View 很快就會力不從心,這時候該換上 SurfaceView。

一、SurfaceView 是什麼

一般情況下,View 的繪製與事件處理都在同一條執行緒(通常是主執行緒)完成,這也是為什麼訪問網路這類長時間操作要丟到背景執行緒——避免阻塞 UI。但反過來說,背景執行緒也不允許修改 UI 元素,例如從後台執行緒去更新自訂 View、觸發它的 onDraw,這是行不通的。

如果你需要在另一條執行緒繪製畫面、需要極快的更新速度,或者單幀渲染本身就相當耗時,那就該用 SurfaceView。它內部持有一個 Surface 物件,而 Surface 可以在背景執行緒中繪製。這個特性決定了它適合的場景:畫面需要迅速更新、對幀率有要求。

使用時要留意幾點:

  • SurfaceView 與 SurfaceHolder.Callback 的相關函式都是從當前視窗執行緒(一般是主執行緒)呼叫,資源狀態要注意與繪製執行緒之間的同步。
  • 繪製執行緒必須先合法取得 Surface 才能開始畫,只有處於 surfaceCreated() 與 surfaceDestroyed() 之間才算合法;當 Surface 類型為 SURFACE_TYPE_PUSH_BUFFERS 時是不合法的。
  • 額外的繪製執行緒會消耗系統資源,用之前先想清楚。

二、基本用法

繼承 SurfaceView 並實作 SurfaceHolder.Callback 的三個方法:

  • surfaceCreated(SurfaceHolder holder):Surface 建立時呼叫,通常在這裡啟動繪圖執行緒。
  • surfaceChanged(SurfaceHolder holder, int format, int width, int height):尺寸或格式變動時呼叫,例如橫竖屏切換。在 surfaceCreated 之後至少會被呼叫一次。
  • surfaceDestroyed(SurfaceHolder holder):Surface 銷毀前呼叫,通常在此停止繪圖執行緒並清理資源。

另外要取得 SurfaceHolder 並加上回調,這三個方法才會被觸發。透過 getHolder() 可以拿到 SurfaceHolder,Surface 就在其中。雖然 Surface 保存了視窗的像素資料,但實務上不會直接跟它打交道,而是用 SurfaceHolder 的 lockCanvas() 或 lockCanvas(Rect dirty) 取得 Canvas,在 Canvas 上繪製來間接修改 Surface 的內容。

若 Surface 尚未建立或不可編輯,lockCanvas 會回傳 null。unlockCanvas 與 lockCanvas 之間的內容不會被快取,所以必須完整重繪;想省一點力氣,可以用 lockCanvas(Rect dirty) 指定一個 dirty 區域,只重畫變動部分,區域外的內容會被保留下來。

取得 Canvas 後,SurfaceView 會持有 Surface 的同步鎖,直到呼叫 unlockCanvasAndPost(Canvas canvas) 才釋放。這個同步機制保證繪製過程中 Surface 不會被銷毀或修改。畫完呼叫 unlockCanvasAndPost,系統就會把結果顯示出來。

另外可以透過 setType 設定繪製類型:

  • SURFACE_TYPE_NORMAL:以 RAM 快取原生資料的普通 Surface。
  • SURFACE_TYPE_HARDWARE:適用於 DMA 引擎與硬體加速的 Surface。
  • SURFACE_TYPE_GPU:適用於 GPU 加速的 Surface。
  • SURFACE_TYPE_PUSH_BUFFERS:不含原生資料,內容由其他物件提供,相機預覽就是這種用法,畫面會比較順。設為這個類型後就不能用 lockCanvas 取得 Canvas 了。

切記:一個 SurfaceView 只有在 surfaceCreated 與 surfaceDestroyed 之間是可用的,其他時間拿不到 Canvas(回傳 null)。

三、實戰:讓精靈沿著螢幕走一圈

下面做個小 demo:一個有四個方向行走動畫的精靈,沿著螢幕四周不停走動。

核心類別 GameView.java:

 public class GameView extends SurfaceView implements SurfaceHolder.Callback {
 //螢幕寬高
 public static int SCREEN_WIDTH;
 public static int SCREEN_HEIGHT;

 private Context mContext;
 private SurfaceHolder mHolder;

 //最大幀數 (1000 / 30)
 private static final int DRAW_INTERVAL = 30;

 private DrawThread mDrawThread;
 private FrameAnimation[] spriteAnimations;
 private Sprite mSprite;

 private int spriteWidth = 0;
 private int spriteHeight = 0;
 private float spriteSpeed = (float) ((500 * SCREEN_WIDTH / 480) * 0.001);
 private int row = 4;
 private int col = 4;

 public GameSurfaceView(Context context) {
 super(context);
 this.mContext = context;
 mHolder = this.getHolder();
 mHolder.addCallback(this);
 initResources();
 mSprite = new Sprite(spriteAnimations, 0, 0, spriteWidth, spriteHeight, spriteSpeed);
 }

 private void initResources() {
 Bitmap[][] spriteImgs = generateBitmapArray(mContext, R.drawable.sprite, row, col);
 spriteAnimations = new FrameAnimation[row];
 for (int i = 0; i < row; i++) {
 Bitmap[] spriteImg = spriteImgs[i];
 FrameAnimation spriteAnimation =
 new FrameAnimation(spriteImg, new int[]{150, 150, 150, 150}, true);
 spriteAnimations[i] = spriteAnimation;
 }
 }

 public Bitmap decodeBitmapFromRes(Context context, int resourseId) {
 BitmapFactory.Options opt = new BitmapFactory.Options();
 opt.inPreferredConfig = Bitmap.Config.RGB_565;
 opt.inPurgeable = true;
 opt.inInputShareable = true;
 InputStream is = context.getResources().openRawResource(resourseId);
 return BitmapFactory.decodeStream(is, null, opt);
 }

 public Bitmap createBitmap(Context context, Bitmap source, int row, int col,
 int rowTotal, int colTotal) {
 return Bitmap.createBitmap(source,
 (col - 1) * source.getWidth() / colTotal,
 (row - 1) * source.getHeight() / rowTotal,
 source.getWidth() / colTotal,
 source.getHeight() / rowTotal);
 }

 public Bitmap[][] generateBitmapArray(Context context, int resourseId, int row, int col) {
 Bitmap bitmaps[][] = new Bitmap[row][col];
 Bitmap source = decodeBitmapFromRes(context, resourseId);
 this.spriteWidth = source.getWidth() / col;
 this.spriteHeight = source.getHeight() / row;
 for (int i = 1; i <= row; i++) {
 for (int j = 1; j <= col; j++) {
 bitmaps[i - 1][j - 1] = createBitmap(context, source, i, j, row, col);
 }
 }
 if (source != null && !source.isRecycled()) {
 source.recycle();
 source = null;
 }
 return bitmaps;
 }

 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }

 public void surfaceCreated(SurfaceHolder holder) {
 if (null == mDrawThread) {
 mDrawThread = new DrawThread();
 mDrawThread.start();
 }
 }

 public void surfaceDestroyed(SurfaceHolder holder) {
 if (null != mDrawThread) {
 mDrawThread.stopThread();
 }
 }

 private class DrawThread extends Thread {
 public boolean isRunning = false;

 public DrawThread() {
 isRunning = true;
 }

 public void stopThread() {
 isRunning = false;
 boolean workIsNotFinish = true;
 while (workIsNotFinish) {
 try {
 this.join();// 保證 run 方法執行完畢
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 workIsNotFinish = false;
 }
 }

 public void run() {
 long deltaTime = 0;
 long tickTime = 0;
 tickTime = System.currentTimeMillis();
 while (isRunning) {
 Canvas canvas = null;
 try {
 synchronized (mHolder) {
 canvas = mHolder.lockCanvas();
 //設置方向
 mSprite.setDirection();
 //更新精靈位置
 mSprite.updatePosition(deltaTime);
 drawSprite(canvas);
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 if (null != mHolder) {
 mHolder.unlockCanvasAndPost(canvas);
 }
 }
 deltaTime = System.currentTimeMillis() - tickTime;
 if (deltaTime < DRAW_INTERVAL) {
 try {
 Thread.sleep(DRAW_INTERVAL - deltaTime);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 tickTime = System.currentTimeMillis();
 }
 }
 }

 private void drawSprite(Canvas canvas) {
 //清屏
 canvas.drawColor(Color.BLACK);
 mSprite.draw(canvas);
 }
 } 

GameView 裡有一條繪圖執行緒 DrawThread,run 方法中依序做:鎖定 Canvas、決定方向、更新位置、繪製精靈、釋放 Canvas,並用 DRAW_INTERVAL 控制幀率。精靈素材是一張大圖,所以先裁切成二維陣列,再用它初始化四個方向的動畫。

Sprite.java:

 public class Sprite {
 public static final int DOWN = 0;
 public static final int LEFT = 1;
 public static final int RIGHT = 2;
 public static final int UP = 3;

 public float x;
 public float y;
 public int width;
 public int height;
 //精靈行走速度
 public double speed;
 //精靈當前行走方向
 public int direction;
 //精靈四個方向的動畫
 public FrameAnimation[] frameAnimations;

 public Sprite(FrameAnimation[] frameAnimations, int positionX, int positionY,
 int width, int height, float speed) {
 this.frameAnimations = frameAnimations;
 this.x = positionX;
 this.y = positionY;
 this.width = width;
 this.height = height;
 this.speed = speed;
 }

 public void updatePosition(long deltaTime) {
 switch (direction) {
 case LEFT:
 //讓移動速度不受機器性能影響:每幀移動距離 = 速度 × 時間間隔
 this.x = this.x - (float) (this.speed * deltaTime);
 break;
 case DOWN:
 this.y = this.y + (float) (this.speed * deltaTime);
 break;
 case RIGHT:
 this.x = this.x + (float) (this.speed * deltaTime);
 break;
 case UP:
 this.y = this.y - (float) (this.speed * deltaTime);
 break;
 }
 }

 /** 根據精靈當前位置判斷是否改變行走方向 */
 public void setDirection() {
 if (this.x <= 0 && (this.y + this.height) < GameSurfaceView.SCREEN_HEIGHT) {
 if (this.x < 0) this.x = 0;
 this.direction = Sprite.DOWN;
 } else if ((this.y + this.height) >= GameSurfaceView.SCREEN_HEIGHT
 && (this.x + this.width) < GameSurfaceView.SCREEN_WIDTH) {
 if ((this.y + this.height) > GameSurfaceView.SCREEN_HEIGHT)
 this.y = GameSurfaceView.SCREEN_HEIGHT - this.height;
 this.direction = Sprite.RIGHT;
 } else if ((this.x + this.width) >= GameSurfaceView.SCREEN_WIDTH && this.y > 0) {
 if ((this.x + this.width) > GameSurfaceView.SCREEN_WIDTH)
 this.x = GameSurfaceView.SCREEN_WIDTH - this.width;
 this.direction = Sprite.UP;
 } else {
 if (this.y < 0) this.y = 0;
 this.direction = Sprite.LEFT;
 }
 }

 public void draw(Canvas canvas) {
 FrameAnimation frameAnimation = frameAnimations[this.direction];
 Bitmap bitmap = frameAnimation.nextFrame();
 if (null != bitmap) {
 canvas.drawBitmap(bitmap, x, y, null);
 }
 }
 } 

精靈類負責依當前位置判斷行走方向,再依方向更新座標,最後畫出自己的動畫。由於動畫是逐幀播放圖片,所以另外封裝了 FrameAnimation:

 public class FrameAnimation {
 /**動畫顯示需要的資源*/
 private Bitmap[] bitmaps;
 /**動畫每幀顯示的時間*/
 private int[] duration;
 /**動畫上一幀顯示的時間*/
 protected Long lastBitmapTime;
 /**動畫顯示的索引值,防止陣列越界*/
 protected int step;
 /**動畫是否重複播放*/
 protected boolean repeat;
 /**動畫重複播放的次數*/
 protected int repeatCount;

 /**
 * @param bitmap: 顯示的圖片
 * @param duration: 圖片顯示的時間
 * @param repeat: 是否重複動畫過程
 */
 public FrameAnimation(Bitmap[] bitmaps, int duration[], boolean repeat) {
 this.bitmaps = bitmaps;
 this.duration = duration;
 this.repeat = repeat;
 lastBitmapTime = null;
 step = 0;
 }

 public Bitmap nextFrame() {
 //判斷 step 是否越界
 if (step >= bitmaps.length) {
 if (!repeat) {
 return null;
 } else {
 lastBitmapTime = null;
 }
 }
 if (null == lastBitmapTime) {
 //第一次執行
 lastBitmapTime = System.currentTimeMillis();
 return bitmaps[step = 0];
 }
 long nowTime = System.currentTimeMillis();
 if (nowTime - lastBitmapTime <= duration[step]) {
 //還在 duration 時間段內,繼續返回當前幀
 //duration 值小於 0 時表示永不失效,通常用於背景
 return bitmaps[step];
 }
 lastBitmapTime = nowTime;
 return bitmaps[step++];//返回下一幀
 }
 } 

FrameAnimation 依每幀的顯示時間決定要回傳哪一幀:沒超過時間就繼續回傳當前幀,超過了就切下一幀。

最後讓 Activity 顯示 GameView,並設定全螢幕:

 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
 WindowManager.LayoutParams.FLAG_FULLSCREEN);
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

 DisplayMetrics outMetrics = new DisplayMetrics();
 this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
 GameSurfaceView.SCREEN_WIDTH = outMetrics.widthPixels;
 GameSurfaceView.SCREEN_HEIGHT = outMetrics.heightPixels;

 GameSurfaceView gameView = new GameSurfaceView(this);
 setContentView(gameView);
 } 

跑起來之後,就能看到一个手持寶劍的武士沿著螢幕邊緣一直走。把精靈素材換成自己的、加上碰撞偵測與背景捲動,一個簡單的遊戲框架就有雛形了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved