android – What is the unit of bitmap.getWidth() or bitmap.getHeight()-ThrowExceptions

Exception or error:

The developers website simply states that getHeight() will return the bitmap’s height, but can someone tell me that is in pixel unit or dp unit?

How to solve:

It’s pixel. In Java code you usually work with pixels, e.g. a view’s width and height.

###

After Hours of Experimenting I found that it actually return height in dp units.You can verify it by changing the device screen in emulator.

###

bitmap.getWidth() returns width in dp unit or densitiy.

To get dpi (density per inch) for a device, use

float dpi = context.getResources().getDisplayMetrics().density;

To convert dp to px

float px = dp * dpi;

and to convert px to dp

float dp = px/dpi;

###

If you read on how android deals with views this not clear at all. See “Supporting Multiple Screeens”. After reading that document I have come to the conclusion that “it depends.” (And I’m still guessing as I have not verified my analysis.) If the View was declared with size “wrap_content”, “fill_parent”, or “dp” then you get “dp”, otherwise you get pixels. If you used “dp” then scaling to pixels is achieved by multiplying by

getResources().getDisplayMetrics().density

For 160 dpi screen, this returns 1.0; for 320 pi screen this returns 2.0.

###

Dividing by getResources()….density.

Leave a Reply

Your email address will not be published. Required fields are marked *