This is the way to go:
private Bitmap mBitmap;
private Canvas mBitmapCanvas;
private Paint mDrawPaint = new Paint();
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
mBitmapCanvas = new Canvas(mBitmap);
}
mBitmapCanvas.drawColor(Color.WHITE); // clear previously drawn stuff
// draw stuff...
mBitmapCanvas.drawLine(....);
canvas.drawBitmap(mBitmap, 0, 0, mDrawPaint);
}
You should avoid, if possible, to allocate memory (new-operator) inside the onDraw(Canvas c)
method. However, you can check if your variable has already been created and avoid re-allocation.
In order to reset your Bitmap
, do not recreate it, use:
mBitmapCanvas.drawColor(Color.WHITE);
instead.