I have square images and need them to scale up to fill the view whilst being positioned in the centre.
I've tried all of the XML options and nothing changes - The image always fills the view and stretches when I switch orientation between Portrait and Landscape modes.
I've now implemented a custom ImageView to override the onMeasure method and set the Drawable image dimensions depending on the screen size. But I have the same problem - the image still stretches in both portrait and landscape mode.
Here is the code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.mypackage.BackgroundImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/backgroundImage"/>
...
The custom ImageView class:
public class BackgroundImageView extends ImageView {
public BackgroundImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final Drawable drawable = this.getDrawable();
if (drawable != null) {
float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
if (imageSideRatio >= viewSideRatio) {
// Image is wider than the display (ratio)
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int)(width / imageSideRatio);
setMeasuredDimension(width, height);
} else {
// Image is taller than the display (ratio)
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = (int)(height * imageSideRatio);
setMeasuredDimension(width, height);
}
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
How can I prevent the image from stretching and instead allow it to overflow the imageview (or crop it)?