1. 程式人生 > >Android中 view的雙緩衝技術

Android中 view的雙緩衝技術

view實現雙緩衝技術

當要繪製的資料量比較大,繪圖時間比較長時,重複繪圖會出現閃爍現象,引起閃爍現象的主要原因是視覺反差比較大。

使用雙緩衝技術可以解決這個問題,Surfaceview預設是使用雙緩衝技術的。

在Android上實現雙緩衝技術的步驟是:

建立一個螢幕大小(實際繪圖區域)的緩衝區(Bitmap),建立一個畫布(Canvas),然後設定畫布的bitmap為建立好的緩衝區,

把需要繪製的影象繪製到緩衝區上。最後把緩衝區中的影象繪製到螢幕上。

具體實現程式碼如下:

public class DrawView4 extends View {
    private int 
screenWidth,screenHeight; public DrawView4(Context context) { super(context); DisplayMetrics dm = context.getResources().getDisplayMetrics(); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; } public Bitmap decodeBitmapFromRes(Context context, int resourceId) { BitmapFactory.Options options =
new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inPurgeable = true; options.inInputShareable = true; InputStream in = context.getResources().openRawResource(resourceId); return BitmapFactory.decodeStream(in, null, options); } @Override protected void onDraw(Canvas canvas) { //1. 建立緩衝畫布 Canvas bufferCanvas = new Canvas(); //2. 建立快取Bitmap Bitmap bufferBitmap = Bitmap.createBitmap
(screenWidth,screenHeight, Bitmap.Config.ARGB_8888); //3. 將緩衝點陣圖設定給緩衝畫布 bufferCanvas.setBitmap(bufferBitmap); //4. 在緩衝畫布上繪製真實的點陣圖 bufferCanvas.drawBitmap(decodeBitmapFromRes(getContext(), R.drawable.ic_launcher), 0, 0, null); //5. 用螢幕的畫布繪製緩衝點陣圖 canvas.drawBitmap(bufferBitmap,0,0, null); }
}