![](/img/trans.png)
[英]How to resize an image to fit imageview with 4 constraints and no width or height parameters while maintaining the aspect ratio?
[英]Scale ImageView to fit screen width/height while maintaining aspect ratio
我正在开发Xamarin上的移动应用程序。
在应用程序中,有一个ImageView
显示的图像太小,无法适应屏幕的宽度。
我想缩放图像以适应屏幕的宽度,同时保持纵横比。
我的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>
结果
两个ImageViews显示a)比屏幕宽度宽的图片和b)比屏幕宽度窄的图片
我尝试过android:scaleType
各种组合android:scaleType
和android:adjustViewBounds="true"
但没有成功。
事实证明它有点难,并且不可能开箱即用。 许多人 有 类似的 问题 。
我最终将@patrick-boos解决方案移植到.Net,如下所示:
扩展的ImageView类
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);
}
}
}
我的axml
<Nsa.BigBrotherUtility.Helpers.DynamicImageView
android:id="@+id/overlayImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
/>
结果
600x600图像现在可以拉伸以填充屏幕宽度,同时保持纵横比
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.