android雙緩衝技術執行個體詳解_Android

來源:互聯網
上載者:User

Android中的SurfaceView類就是雙緩衝機制。因此,在進行Android遊戲開發時應盡量使用SurfaceView而不要使用View,這樣的話效率較高,並且SurfaceView的功能也更加完善。為了更容易的瞭解雙緩衝技術,下面介紹用View實現雙緩衝的方法。

在此需要說明一下,雙緩衝的核心技術就是先通過setBitmap方法將要繪製的所有的圖形繪製到一個Bitmap上,然後再來調用drawBitmap方法繪製出這個Bitmap,顯示在螢幕上。其具體的實現代碼如下:

先貼出View類代碼:

package com.lbz.pack.test;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Bitmap.Config;import android.graphics.drawable.BitmapDrawable;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;public class GameView extends View implements Runnable{ /* 聲明Bitmap對象 */ Bitmap mBitQQ = null; Paint  mPaint = null; /* 建立一個緩衝區 */ Bitmap mSCBitmap = null; /* 建立Canvas對象 */ Canvas mCanvas = null;   public GameView(Context context) { super(context); /* 裝載資源 */ mBitQQ = ((BitmapDrawable) getResources().getDrawable(R.drawable.qq)).getBitmap(); /* 建立螢幕大小的緩衝區 */ mSCBitmap=Bitmap.createBitmap(320, 480, Config.ARGB_8888);  /* 建立Canvas */ mCanvas = new Canvas();  /* 設定將內容繪製在mSCBitmap上 */ mCanvas.setBitmap(mSCBitmap);  mPaint = new Paint(); /* 將mBitQQ繪製到mSCBitmap上 */ mCanvas.drawBitmap(mBitQQ, 0, 0, mPaint); /* 開啟線程 */ new Thread(this).start(); } public void onDraw(Canvas canvas) { super.onDraw(canvas); /* 將mSCBitmap顯示到螢幕上 */ canvas.drawBitmap(mSCBitmap, 0, 0, mPaint); } // 觸筆事件 public boolean onTouchEvent(MotionEvent event) { return true; } // 按鍵按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } // 按鍵彈起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return false; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } /** * 線程處理 */ public void run() { while (!Thread.currentThread().isInterrupted()) {  try  {  Thread.sleep(100);  }  catch (InterruptedException e)  {  Thread.currentThread().interrupt();  }  //使用postInvalidate可以直接線上程中更新介面  postInvalidate(); } }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.