How do I add, say, a line to an already drawn view?
I tried grabbing the canvas from the draw method and using it to draw to, but it doesn’t seem to be working.
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas = canvas;
//drawing code here
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(10);
paint.setStyle(Style.FILL);
mCanvas.drawLine(0, 0, 50, 50, paint);
}
}
}
Do the following steps:
ACTION_DOWNwas triggered.invalidate()call in your case blockonDraw()draw your line if the flag is trueedit
You need to understand the drawing process to understand why saving the canvas object doesn’t work.
Android works with two buffers that are flipped (naming them buffer A and B). You draw always on the buffer that isn’t visible. After you finished drawing, the buffers will be switched and you will see what you have drawn. Basically the canvas will be locked (to prevent flipping while drawing on the back buffer), and this canvas object will be provided to each view that has requested redrawing. After that the canvas will be unlocked which triggers that the buffers are switched. In that moment this canvas object may still be there, but every drawing you do on it will never be displayed.
A bit more information can be found on my blog 2D Drawing Series