Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Difference between canvas.drawBitmap and BitmapDrawable.draw?

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:

  1. Using canvas.drawBitmap() and extract the Bitmap from the drawable using getBitmap()

  2. 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

like image 604
Sven Avatar asked Jul 13 '11 15:07

Sven


People also ask

Can we draw directly on canvas Android?

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.

What is the use of bitmap canvas and Paint class?

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.

What is the difference between canvas and 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.

How to draw bitmap on canvas in Android?

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.


1 Answers

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!

like image 80
Emir Kuljanin Avatar answered Oct 15 '22 21:10

Emir Kuljanin