将ImageView缩放到适应屏幕的宽度/高度,同时保持纵横比。

4

我正在使用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>

结果

两个ImageView显示a)一张比屏幕宽的图片和b)一张比屏幕窄的图片

两个ImageView分别显示a)一张比屏幕宽的图片和b)一张比屏幕窄的图片

我尝试了各种android:scaleTypeandroid:adjustViewBounds="true"的组合,但都没有成功。

1个回答

3

这个问题有点难,不能直接解决。许多人 遇到了 类似的 问题

最终,我像这样将@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的图像会拉伸以填充屏幕宽度,同时保持纵横比。

technical drawing being stretched to fit width of screen


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接