I need to scale an Image to fit the displayable area of the screen. Currently, I am calculating the scale ratio using constants 320 and 480(width x height) (i.e. emulator skin: HVGA-P screen size).
It is fair to assume that different devices will have different width and height. For my code to become independent of this, I need the width and height of the device screen at run time.
I tried canvas.getHeight() and canvas.getWidth() but it gave a result, I could not understand.(For HVGA-P, I got width = 603, height = 444)
Is there a class that can help here?
Also, when I rotate the emulator by 90 degrees using the PgUp button on the numpad, the emulator display changes from portrait to landscape, does this happen on actual device too?
When the screen orientation changes (both on the emulator and on a real G1 when you flip out the keyboard), you can choose to have your application restarted with the new orientation or you can choose to get a "configuration change" event that you handle yourself. For more details see Mark's great description here:
View#getWidth() won't give you a meaningful answer until the view has been measured, and when it does, it still doesn't give you the width of the display, which is what I believe the original poster was asking.
Here's how you do it:
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
I tried getWidth() and getHeight() in the constructor of my view Object. Both the functions returned 0. I was not aware that we'd have to measure the view first; will try that and see what the functions return.
A common mistake made by new Android developers is to use
the width and height of a view inside its constructor. When
a view’s constructor is called, Android doesn’t know yet how
big the view will be, so the sizes are set to zero. The real sizes
are calculated during the layout stage, which occurs after
construction but before anything is drawn. You can use the
onSizeChanged( )method to be notified of the values when they
are known, or you can use the getWidth( ) and getHeight( )methods
later, such as in the onDraw( ) method.
I am not big fan of calling methods of an object from within its constructor (since the object is not fully constructed yet). But I wanted to resize my bitmap(only once) when it is first drawn on the canvas and I thought the constructor would be the right place.