Android自定义view绘制矩形,在这我给出两种方式:
1.常用的,大家都使用drawRect(RectF rectF, Paint paint)
2.Path
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(200, 200);
canvas.drawPath(path, paint);
当然在大量绘制过程中,需要我们清屏,来显示新的内容
误区一:我设置了一个clearDraw()的子函数,在子函数里设置:
[java] view plaincopy
void clearDraw()
{
/对画布进行清屏/
Canvas canvas = sh.lockCanvas();
if(canvas!=null){
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawPaint(paint);
//canvas.drawColor(Color.BLUE);
}
sh.unlockCanvasAndPost(canvas);
}
[java] view plain copy 在CODE上查看代码片派生到我的代码片
void clearDraw()
{
/对画布进行清屏/
Canvas canvas = sh.lockCanvas();
if(canvas!=null){
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawPaint(paint);
//canvas.drawColor(Color.BLUE);
}
sh.unlockCanvasAndPost(canvas);
}
然后每次按下按键进行识别物体的算法前,先进行清屏。得到的效果是,确实清屏了,但第二次画出矩形框时,第一次的矩形框就会蹦出来了。依次类推,的确会出现短暂的清屏效果,只是最终还是不能清屏。
误区二:
参考这里,http://www.eoeandroid.com/thread-79664-1-1.html,我用canvas.drawLine(),也就是说将paint设置为清屏模式的paint,把所有画的图形用这个画笔重新画一次,但遗憾的是这种效果也和第一种一样。
误区三:
有人提议用canvas的save和restore来解决,但很遗憾根本不是这么回事。参考:http://www.devdiv.com/article-1948-1.html
正确的方法是这样的,在SurfaceView里定义一个画图的方法,在这个画图方法的开始部分执行清屏,重点就三句话:
[java] view plaincopy
public void drawLine(Point p1, Point p2, Point p3)
{
Canvas canvas = sh.lockCanvas();
canvas.drawColor(Color.TRANSPARENT);
Paint p = new Paint();
//清屏
p.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC));
p.setAntiAlias(true);
p.setColor(Color.RED);
p.setStyle(Paint.Style.FILL);
canvas.drawLine(0,0, 500, 500, p);
sh.unlockCanvasAndPost(canvas);
}
[java] view plain copy 在CODE上查看代码片派生到我的代码片
public void drawLine(Point p1, Point p2, Point p3)
{
Canvas canvas = sh.lockCanvas();
canvas.drawColor(Color.TRANSPARENT);
Paint p = new Paint();
//清屏
p.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC));
p.setAntiAlias(true);
p.setColor(Color.RED);
p.setStyle(Paint.Style.FILL);
canvas.drawLine(0,0, 500, 500, p);
sh.unlockCanvasAndPost(canvas);
}
清屏:
Paint p = new Paint();
//清屏
p.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC));