Android: How to fill the screen with an image while maintaining aspect ratio and handle both landscape and portrait orientations

StackOverflow https://stackoverflow.com/questions/23512046

Question

I have square images that I use as backgrounds for my Relative Layouts.

I would like to stretch the images to fill the screen and maintain the aspect ratio. The image should be centered such that the excess is cropped out depending on the orientation, landscape or portrait.

I have searched through many posting on how to achieve this, tried many different things (both programmatically and in the xml), and had no success.

Can this be done on the background? Do I instead need to use an ImageView in my layout? How would I do this?

It seems like this should be doable, and it's almost trivial on the iPhone, but seems a major hassle on android. I really feel like there is something I must be missing.

Was it helpful?

Solution

Found a solution that does exactly what I want.

Always seems obvious and simple AFTER you find the right bit of magic.


activity_instructions.xml

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="center" />

InstructionsActivity.java

Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, myDimension, myDimension, true);

ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(scaledBitmap);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top