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

來源:互聯網
上載者:User

  雙緩衝技術就是當使用者操作介面完成後,會有一個緩衝區儲存使用者操作的結果。

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

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

  package com.example.phonegaptest;

  import android.content.Context;

  import android.graphics.Bitmap;

  import android.graphics.Bitmap.Config;

  import android.graphics.Canvas;

  import android.graphics.Color;

  import android.graphics.Paint;

  import android.graphics.Path;

  import android.util.AttributeSet;

  import android.view.MotionEvent;

  import android.view.View;

  public class DrawView extends View {

  float preX;

  float preY;

  private Path path;

  public Paint paint = null;

  final int VIEW_WIDTH = 320;

  final int VIEW_HEIGHT = 480;

  Bitmap cacheBitmap = null;

  Canvas cacheCanvas = null;

  public DrawView(Context context, AttributeSet set) {

  super(context, set);

  cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH, VIEW_HEIGHT,

  Config.ARGB_8888);

  cacheCanvas = new Canvas();

  path = new Path();

  cacheCanvas.setBitmap(cacheBitmap);

  paint = new Paint(Paint.DITHER_FLAG);

  paint.setColor(Color.RED);

  paint.setStyle(Paint.Style.STROKE);

  paint.setStrokeWidth(1);

  paint.setAntiAlias(true);

  paint.setDither(true);

  }

  @Override

  public boolean onTouchEvent(MotionEvent event) {

  float x = event.getX();

  float y = event.getY();

  switch (event.getAction()) {

  case MotionEvent.ACTION_DOWN:

  path.moveTo(x, y);

  preX = x;

  preY = y;

  break;

  case MotionEvent.ACTION_MOVE:

  path.quadTo(preX, preY, x, y);

  preX = x;

  preY = y;

  break;

  case MotionEvent.ACTION_UP:

  cacheCanvas.drawPath(path, paint);

  path.reset();

  break;

  }

  invalidate();

  return true;

  }

  @Override

  protected void onDraw(Canvas canvas) {

  super.onDraw(canvas);

  Paint bmpPaint = new Paint();

  canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);

  canvas.drawPath(path, paint);

  }

  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.