Imagine I have a Bitmap and I need to draw on it. For that I need to wrap it in a Canvas.
Can I wrap it as follows:
Bitmap mBitmap;
public void drawDrawable(Drawable d){
d.draw(new Canvas(mBitmap));
}
public void drawListOfPathsInRed(List<Path> list){
Paint paint = new Paint();
for(Path path : list)
new Canvas(mBitmap).drawPath(path, paint);
}
How bad would that be? Is there any noticeable overhead to creating many Canvases or any other issue with it?
Canvas
itself is not a huge deal, it's a pretty "light" object, but when we're talking about drawing, we really need every bit of performance we can get (more info here: Optimizing the view). To that end, you could move the Canvas
creation outside your drawing method, and reuse it with the setBitmap
method:
Bitmap mBitmap;
Canvas mCanvas = Canvas();
Paint mPaint = new Paint(); // You should also reuse your Paint object
public void drawDrawable(Drawable d) {
mCanvas.setBitmap(mBitmap);
d.draw(mCanvas);
}
public void drawListOfPathsInRed(List<Path> list){
canvas.setBitmap(mBitmap)
for (Path path : list) {
canvas.drawPath(path, paint);
}
}
To go a step further, you could also extract the call to mCanvas.setBitmap
from the drawing step, by doing right after setting your mBitmap
variable.