android - 缩放 ImageView 以适应屏幕宽度/高度,同时保持纵横比

标签 android xamarin

我正在 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) 比屏幕宽度窄的图片

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

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

最佳答案

原来有点难,开箱即用是不可能的。 Many have similar problems .

我最终移植了 @patrick-boos solution像这样到 .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 图像现在可以拉伸(stretch)以填充屏幕宽度,同时保持纵横比

technical drawing being stretched to fit width of screen

关于android - 缩放 ImageView 以适应屏幕宽度/高度,同时保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209873/

相关文章:

Android 云测试实验室与 Firebase 测试实验室

Android:如何在当前 Activity 进程中启动外部 Activity ?

android - 一旦将预期的消息传递到 android 应用程序,我的服务器能否收到来自 GCM 的确认?

android - 样式在 android webview 中不起作用

android - 如何在 Android 应用程序中每天重复一个 Action ?

android - 如何在android xamarin中调整图像按钮的大小?

android - 无法登录手动安装的 APK 的 Google Play 服务

iOS 9 通用链接转发按钮永远中断深度链接,直到我删除手机设置

android - Xamarin 安卓 : Change UI TextView text from Service or Receiver

c# - 在 PCL,Xamarin 中读取文件