程序先将绘制的内容绘制到Bitmap图片缓冲区上,再将Bitmap绘制到View上,防止此前绘制内容的消失
绘制工具自定义View类
public class DrawView extends View
{
float preX;
float preY;
private Path path;
public Paint paint = null;
final int VIEW_WIDTH = 960;
final int VIEW_HEIGHT = 1440;
// 定义一个内存中的图片,该图片将作为缓冲区
Bitmap cacheBitmap = null;
// 定义cacheBitmap上的Canvas对象
Canvas cacheCanvas = null;
public DrawView(Context context, AttributeSet set)
{
super(context, set);
// 创建一个与该View相同大小的缓存区
cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH
, VIEW_HEIGHT , 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;
}
//通知View组件重绘
invalidate();
// 返回true表明处理方法已经处理该事件
return true;
}
@Override
public void onDraw(Canvas canvas)
{
Paint bmpPaint = new Paint();
// 将cacheBitmap绘制到该View组件上
canvas.drawBitmap(cacheBitmap , 0 , 0 , bmpPaint);
// 沿着path绘制
canvas.drawPath(path, paint);
}
}
在xml文件中布置改类后,在activity中打开该xml文件即可实现画图板效果
网友评论