user1419072
user1419072

Reputation: 1

How to dynamically draw bitmaps to a Canvas in Android?

Here is the scenario of the issue . A custom view which is a canvas on which I need to draw . 2 buttons beneath it ,lets call them A and B When A is clicked -> Image A is drawn to the above canvas . When B is clicked -> Image B is drawn to the above canvas .

The issue demands that the previously drawn image on canvas must be preserved . That is if you click button A followed by button B then the canvas must contain two images . So the previous images need to be preserved.

Problem : How do you achieve this ? Possible solution 1 : Create an ArrayList and keep adding images to this arrayList . Pass the updated arrayList to canvas onDraw method and redraw every single image for every button click .

Possible solution 2 : There has to be some method to preserve the state of the canvas so that on each button click you draw on canvas's last preserved state and draw only the new image .

Further Requirements : The Images drawn to canvas could be dragged so need to keep track of updated positions .

I am at an impasse and couldn't find a good tutorial or a book tackling such requirement , any help is appreciated .

Upvotes: 0

Views: 1766

Answers (1)

AterLux
AterLux

Reputation: 4654

You can create the Bitmap, and draw what you want on it.

Bitmap mBitmap;

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    if (changed) {
        if (mBitmap != null) {
            mBitmap.recycle();
            mBitmap = null;
        }
        mBitmap = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888);
        redrawAllYourStuffTo(mBitmap);
    }
}

when button is pressed, you can draw directly to bitmap, like this:

Canvas canvas = new Canvas(mBitmap);
canvas. ... // draw operations.

// after the bitmap canvas drawing finished, call
invalidate();

in onDraw just paint your bitmap

protected void onDraw(Canvas canvas) {
   canvas.drawBitmap(mBitmap, 0, 0, null);
}

Upvotes: 2

Related Questions