Draw From Old Canvas - Android

2019-04-02 14:35发布

I'm making an App that needs to be able to draw new graphics on top of the last set.

This is my current onDraw() method -

protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.WHITE);

    if(points.size() > 0) {
        //do some stuff here - this is all working ok
        canvas.drawLine(p1.x, p1.y, p2.x, p2.y, linePaint);
    }   
}

Basically, I need to draw the new graphics as a layer on top of the last, so what I'm looking for is a way to carry the image of the last canvas to the current.

I have tried to figure it out myself using the canvas.setBitmap() method but it acts very funny.

Any help appreciated :)

P.S if it's needed, the the class extends SurfaceView and implements SurfaceHolder.Callback

Edit: This is what I have tried in the onDraw() method but it just force closes

if(bitmap != null) {
        canvas.drawBitmap(bitmap, 0, 0, paint);
        canvas.setBitmap(bitmap);  
    }

2条回答
何必那么认真
2楼-- · 2019-04-02 15:12

Found the answer myself :)

@Override
protected void onDraw(Canvas c) {

if(bitmap != null && canvas != null) { 
    canvas.drawLine(p1.x, p1.y, p2.x, p2.y, linePaint);
    c.drawBitmap(bitmap, 0, 0, linePaint);  
}
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
}

Works exactly as intended, it creates the effect of drawing on top of the old canvas continuously

查看更多
We Are One
3楼-- · 2019-04-02 15:15

You will have to store the previous image persistently onto a ArrayList, and during ondraw, loop through the ArrayList to redraw all items.

something like this:

for (Graphic graphic : _graphics) {
    bitmap = graphic.getBitmap();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
查看更多
登录 后发表回答