How to dynamically draw bitmaps to a Canvas in Android?

让人想犯罪 __ 提交于 2019-12-25 03:08:10

问题


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 .


回答1:


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);
}


来源:https://stackoverflow.com/questions/31412638/how-to-dynamically-draw-bitmaps-to-a-canvas-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!