Frage

In my custom view I call createBitmap in onDraw method. I have doubts, is it correct to create bitmap on any time in onDraw? Any time when onDraw called, I create new bitmap, but what would happen to older one?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top