Reputation: 1832
I'm developing a mobile app on Xamarin.
In the app, there's an ImageView
displaying an image that is too small to fit the width of the screen.
I want to scale the image to fit the width of the screen while maintaining the aspect ratio.
My axml
<LinearLayout
android:id="@+id/overlayImageContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/overlayImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter"/>
</LinearLayout>
The result
Two ImageViews displaying a) a picture that is wider than the width of the screen and b) a picture that is narrower than the width of the screen
I've tried various combinations of android:scaleType
and android:adjustViewBounds="true"
without success.
Upvotes: 4
Views: 3139
Reputation: 1832
It turned out to be a bit hard, and not possible out of the box. Many have similar problems.
I ended up porting @patrick-boos solution to .Net like so:
Extended ImageView Class
using Android.Content;
using Android.Util;
using Android.Widget;
namespace Nsa.BigBrotherUtility.Helpers
{
/// <summary>
/// DynamicImageView is a helper extension that overrides OnMeasure in order to scale the said image
/// to fit the entire width/or height of the parent container.
/// </summary>
public class DynamicImageView : ImageView
{
public DynamicImageView(Context context, IAttributeSet attributeSet) : base(context, attributeSet)
{
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = MeasureSpec.GetSize(widthMeasureSpec);
int height = width * Drawable.IntrinsicHeight / Drawable.IntrinsicWidth;
SetMeasuredDimension(width, height);
}
}
}
My axml
<Nsa.BigBrotherUtility.Helpers.DynamicImageView
android:id="@+id/overlayImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
/>
The result
The 600x600 image now stretches to fill width of screen while maintaining aspect ratio
Upvotes: 3