When I want to draw a BitmapDrawable to a Canvas in Android, there are two possibilities that do the same and I don't know which one to prefer:
Using canvas.drawBitmap() and extract the Bitmap from the drawable using getBitmap()
Using drawable.draw(canvas), passing the canvas as an argument to the drawable.
I'm using the first option now, but it seems completely arbitrary as I can't see any difference.
Thanks for your answers
To draw onto a canvas in Android, you will need four things: A bitmap or a view — to hold the pixels where the canvas will be drawn. Canvas — to run the drawing commands on. Drawing commands — to indicate to the canvas what to draw.
Canvas API is a drawing framework that is provided in Android, with the help of which we can create custom shapes like rectangle, circle, and many more in our UI design. With the help of this API, we can draw any type of shape for our app. The drawing of the different shapes is done using Bitmap.
Canvas is the place or medium where perfroms/executes the operation of drawing, and Bitmap is responsible for storing the pixel of the picture you draw. Bitmap are close to OS, it is an array of data describing pixels.
Draw the specified bitmap, with its top/left corner at (x,y), using the specified paint, transformed by the current matrix. Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle. Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle.
Never do option number 1 the way you do it. Instead of creating a bitmap out of a drawable every time you want to draw it, create a bitmap in the first place. That is, don't create a Drawable if you are going to draw a bitmap. Create a bitmap like this:
mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.myImage);
mBitmap = Bitmap.createScaledBitmap(mBitmap, width, height, true);
And this is something you do just once. After that, just draw like you do (canvas.drawbitmap()).
As for option number 2, you are doing it correctly.
Now, there are some differences. Option 1 is faster to draw and usually good for background images. There is a significant change to FPS depending on if you draw a bitmap or drawable. Bitmaps are faster.
Option 2 is the way to go if you need to things like scaling, moving and other kinds of manipulations of the image. Not as fast but there's no other option if you want to do any of those things just mentioned.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With