Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Drawing on a new canvas

I've created a custom view by extending View.

    public class CustomView extends View {
        private Canvas canvas2;
        private Bitmap backingBitmap;

In CustomView's constructor, I have the following code:

backingBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
canvas2 = new Canvas(backingBitmap);

In onDraw, I have:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(100, 100, 50, paint);
    canvas2.drawCircle(0, 0, 10, paint);
}

I can see the circle that gets drawn using "canvas" object, but not the one that's drawn using "canvas2" object. My understanding is that one needs only create a mutable Bitmap and make it a Canvas' backing bitmap. Can someone point out what's wrong here?

Bonus question: Where does the custom canvas object get created on the screen, and how would one set its position?

Reason for creating multiple canvases: I have a SurfaceView which encompasses the entire screen. So, basically its canvas covers the entire screen. I need a make a window-like rectangle within the screen and stuff needs to animate within the bounds of that window. Basically, if you translate an image within this window, the image shouldn't get drawn outside the window's bounds.

Cheers!

like image 357
Dev N Avatar asked Mar 23 '23 00:03

Dev N


1 Answers

I figured out what was wrong with my understanding. It all seems so simple now! This link helped.

Basically, when we create a Canvas object, it's creating an offscreen canvas that holds our drawing calls. This Canvas object needs to be backed by a mutable Bitmap, so that all the drawings finally get stored onto this Bitmap. Once the drawing is done, you can draw the mutable bitmap using the canvas that is tied to the surface (the canvas that you get in onDraw).

In my code, I made the following changes to get it working.

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(100, 100, 50, paint);
    canvas2.drawCircle(25, 25, 25, paint);
    canvas.drawBitmap(backingBitmap, 200, 90, paint);
}
like image 163
Dev N Avatar answered Apr 01 '23 03:04

Dev N