简体   繁体   English

如何在Android中将位图动态绘制到Canvas?

[英]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 . 它下面的2个按钮,将它们分别称为A和B。单击A->将图像A绘制到上面的画布上。 When B is clicked -> Image B is drawn to the above canvas . 当单击B时->将图像B绘制到上述画布上。

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 . 也就是说,如果您单击按钮A,然后单击按钮B,则画布必须包含两个图像。 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 . 可能的解决方案1:创建一个ArrayList并继续向该arrayList添加图像。 Pass the updated arrayList to canvas onDraw method and redraw every single image for every button click . 将更新的arrayList传递给canvas onDraw方法,并为每一次单击按钮重绘每个图像。

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 . 可能的解决方案2:必须有某种方法可以保留画布的状态,以便在单击每个按钮时都可以绘制画布的最后保留状态,并且仅绘制新图像。

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 . 我陷入僵局,找不到满足这样要求的好的教程或书,对此有所帮助。

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 onDraw中只需绘制您的位图

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM