public class MyView extends View{
public static Paint paint = null;
public static Canvas cacheCanvas = null;
private Path path;
Bitmap cacheBitmap = null;
public static int PEN_WIDTH = 10;
public static int PAINT_STATUS = 0;
private static int m_strokeColor = Color.RED;
float preX;
float preY;
class DrawPath{
Path path;
Paint paint;
}
private static ArrayList savePath;
private static ArrayList deletePath;
private DrawPath dp;
public SmartpadView(Context context,AttributeSet attrs) {
super(context,attrs);
initCanvas();
initPaint();
savePath = new ArrayList();
deletePath = new ArrayList();
}
public void initCanvas() {
cacheBitmap = Bitmap.createBitmap(3000,2000,Bitmap.Config.ARGB_8888);
cacheCanvas = new Canvas(cacheBitmap);
path = new Path();
cacheCanvas.setBitmap(cacheBitmap);
}
public void initPaint(){
paint = new Paint(Paint.DITHER_FLAG);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(PEN_WIDTH);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
public void onDraw(Canvas canvas) {
Paint bmpPaint = new Paint();
canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint); // ②
canvas.drawPath(path, paint);
}
@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:
dp = new DrawPath();
dp.path = path;
dp.paint = paint;
savePath.add(dp);
cacheCanvas.drawPath(path, paint); // ①
path.reset();
break;
}
invalidate();
return true;
}
public void undo(){
if(savePath!=null&&savePath.size()>0){
initCanvas();
DrawPath temp=savePath.get(savePath.size()-1);
deletePath.add(temp);
savePath.remove(savePath.size()-1);
for(int i=0;i
System.out.println(“撤销0”);
DrawPath dp = savePath.get(i);
cacheCanvas.drawPath(dp.path, dp.paint);
}
invalidate();// 刷新
}
}
public void redo(){
if(deletePath!=null&&deletePath.size()>0){
DrawPath temp=deletePath.get(deletePath.size()-1);
savePath.add(temp);
deletePath.remove(deletePath.size()-1);
cacheCanvas.drawPath(temp.path, temp.paint);
invalidate();
}
}
}
解决方案
20
無法正常運行是甚麼情況, 運行時錯誤
CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明android:画图板的撤销和恢复功能无法正常运行!