我想使用多条直线绘制自定义形状。为此,我使用了画布。但我只能画一条线。当我画第二,之前消失。 我的代码已经给出了。
public class CanvasBackground extends View {
public Paint paint;
public Context context;
public Canvas canvas;
public ScaleGestureDetector scaleGestureDetector;
float scalfactor = 1f;
boolean isDrawing;
private PointF startPoint, endPoint;
public CanvasBackground(Context context) {
super(context);
this.context = context;
paint = new Paint();
scaleGestureDetector = new ScaleGestureDetector(context, new CanvasScale());
setDrawingCacheEnabled(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
canvas.save();
DrawingZoomingCanvas(canvas);
DrawingLine(canvas);
canvas.restore();
Log.e("OnDraw >>>", "CALLING");
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startPoint = new PointF(event.getX(), event.getY());
endPoint = new PointF();
isDrawing = true;
break;
case MotionEvent.ACTION_MOVE:
if (isDrawing) {
endPoint.x = event.getX();
endPoint.y = event.getY();
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (isDrawing) {
endPoint.x = event.getX();
endPoint.y = event.getY();
//isDrawing = false;
invalidate();
}
break;
default:
break;
}
//scaleGestureDetector.onTouchEvent(event);
Log.e("OnTouch >>>", "CALLING" + isDrawing);
return true;
}
//drawing Matrix Canvas With Zoom
private void DrawingZoomingCanvas(Canvas canvas) {
//drawing Matarix
canvas.translate(scalfactor * 10, scalfactor * 10);
canvas.scale(scalfactor, scalfactor);
paint.setColor(Color.rgb(220, 220, 220));
for (int i = 0; i <= canvas.getHeight() * scalfactor; i += 10) {
canvas.drawLine(i, 0, i, canvas.getHeight(), paint);
canvas.drawLine(0, i, canvas.getWidth(), i, paint);
}
}
//drawing a line
private void DrawingLine(Canvas canvas) {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
if (isDrawing)
canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
}
private class CanvasScale extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scalfactor *= scaleGestureDetector.getScaleFactor();
scalfactor = Math.max(0.1f, Math.min(scalfactor, 10.0f));
invalidate();
return true;
}
}
}
答案 0 :(得分:0)
每次画线时都会清除画布,因此在绘制新线时前一行将被删除。
您需要将以前的行存储在位图中,以便在绘制新的行时绘制这些行。