歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用雙緩沖技術實現Android畫板應用

使用雙緩沖技術實現Android畫板應用

日期:2017/3/1 10:10:14   编辑:Linux編程

什麼是雙緩沖技術?雙緩沖技術就是當用戶操作界面完成後,會有一個緩沖區保存用戶操作的結果。

為什麼要使用雙緩沖技術?拿Android 游戲開發來說,界面貞每次都是全部重畫的,也就說畫了新的,舊的就沒了,所以需要使用雙緩沖技術保存之前的內容。

如何實現雙緩沖?使用一個Bitmap對象保留之前的畫布即可。

  1. package com.example.phonegaptest;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.Bitmap.Config;
  5. import android.graphics.Canvas;
  6. import android.graphics.Color;
  7. import android.graphics.Paint;
  8. import android.graphics.Path;
  9. import android.util.AttributeSet;
  10. import android.view.MotionEvent;
  11. import android.view.View;
  12. public class DrawView extends View {
  13. float preX;
  14. float preY;
  15. private Path path;
  16. public Paint paint = null;
  17. final int VIEW_WIDTH = 320;
  18. final int VIEW_HEIGHT = 480;
  19. Bitmap cacheBitmap = null;
  20. Canvas cacheCanvas = null;
  21. public DrawView(Context context, AttributeSet set) {
  22. super(context, set);
  23. cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH, VIEW_HEIGHT,
  24. Config.ARGB_8888);
  25. cacheCanvas = new Canvas();
  26. path = new Path();
  27. cacheCanvas.setBitmap(cacheBitmap);
  28. paint = new Paint(Paint.DITHER_FLAG);
  29. paint.setColor(Color.RED);
  30. paint.setStyle(Paint.Style.STROKE);
  31. paint.setStrokeWidth(1);
  32. paint.setAntiAlias(true);
  33. paint.setDither(true);
  34. }
  35. @Override
  36. public boolean onTouchEvent(MotionEvent event) {
  37. float x = event.getX();
  38. float y = event.getY();
  39. switch (event.getAction()) {
  40. case MotionEvent.ACTION_DOWN:
  41. path.moveTo(x, y);
  42. preX = x;
  43. preY = y;
  44. break;
  45. case MotionEvent.ACTION_MOVE:
  46. path.quadTo(preX, preY, x, y);
  47. preX = x;
  48. preY = y;
  49. break;
  50. case MotionEvent.ACTION_UP:
  51. cacheCanvas.drawPath(path, paint);
  52. path.reset();
  53. break;
  54. }
  55. invalidate();
  56. return true;
  57. }
  58. @Override
  59. protected void onDraw(Canvas canvas) {
  60. super.onDraw(canvas);
  61. Paint bmpPaint = new Paint();
  62. canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);
  63. canvas.drawPath(path, paint);
  64. }
  65. }
Copyright © Linux教程網 All Rights Reserved