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

문제

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.

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top