使用双缓冲技术实现简单画图板

所谓双缓冲技术其实很简单:当程序需要在指定的View上进行绘制时,程序并不直接绘制到该View组件上,而是先绘制到一个内存中的Bitmap图片上(缓冲)上,等到内存中的Bitmap绘制好了之后,再一次性地将Bitmap绘制到View组件上。本文实现一个简单的画图板,代码如下:

Activity:

package com.lovo.activity;

import com.lovo.testdraw.R;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

}


自定义组件类:

package com.lovo.view;

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;
	private Paint paint;
	// 定义一个内存中的图片,该图片将作为缓冲区
	Bitmap cacheBitmap = null;
	// 定义cacheBitmap上的Canvas对象
	Canvas cacheCanvas = null;

	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// 创建一个与该View相同大小的缓冲区
		cacheBitmap = Bitmap.createBitmap(550, 800, Config.ARGB_8888);
		cacheCanvas = new Canvas();
		path = new Path();
		// 设置cacheCanvas将会绘制到内存中的cacheBitmap
		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();
		// 返回true表明处理方法已经处理该事件
		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Paint bmpPaint = new Paint();
		// 将cacheBitmap绘制到该View组件上
		canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);
		// 沿着path绘制
		canvas.drawPath(path, paint);
	}
}


 

你可能感兴趣的:(android,画图板,双缓冲技术)