Search code examples
androiduser-interfacescreen-resolutionaspect-ratio

Handling different screen resolutions for background images in Android


My Android app (a text-based game) uses background images a lot in order to provide a better visual ambiance. For example, if the action in the game takes you into a tavern, then you get a background image of a tavern in the game. This is a vast improvement, graphically, over the boring black background that you would otherwise get.

It is also a problem, however, since android:background always stretches to the dimensions of the screen. The result is that the background images look very bad if the player switches between portrait and landscape mode. And to make matters worse, many devices have very different aspect ratios (e.g., 320x480 mdpi, 480x800 hdpi, and 480x852 hdpi) and even more variations are coming.

How do others solve this problem? Having individual images for the main resolutions/orientations is not an option for me, as this would result in the apk growing too large.


Solution

  • I would suggest you get the width and height of your current view. Right now I am not sure what functions will give you these values but I am sure it is possible. With that you can then calculate an aspect ratio. I'd make the images something like 1000x1000 and just show a certain part of the image, so that the aspect ratio will not be wrong.
    I have the same problem with the camera. So my solution was to pick one of the two values, width or height, as fixed, and calculate the correct other value according to the aspect ratio. I'm not sure if there are functions already to just show a part of the image, but I am sure you could write something to copy just a part of the image and show that part.

    The drawback is of course that you will be showing just a part of the background. Since the general aspect ratio of the phones is however somewhere between 1:1.3 and 1:1.8 I guess it wouldn't be a too big problem. I for one would rather see the part of an image in the correct way, than looking at an ugly stretched image.