Android: 如何调整图像大小以填充父图像?

Android: How to resize image to fill parent?

我正在开发显示图像的应用程序,我需要创建一个以 1:1 纵横比显示大图像的视图。

首先,我有 72x72 分辨率的缩略图。我已将它们放在 ImageView 中,但即使我添加参数 android:width="fill_parent"android:height="wrap_content",图像也不会不是 ImageView 的大小,而是仅居中中期。

我尝试添加参数 android:scaleType="centerCrop" 以水平调整图像大小,但高度保持不变。

如何设置我的 ImageView 以便它在所有设备上的宽度与父视图一样,高度也应该一样。

我可以通过编程方式执行此操作,但我需要能够在 XML 中执行此操作。

我的XML文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    // The ImageView I am talking about above
    <ImageView
        android:id="@+id/invitation_imageview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="1dp"
        android:scaleType="centerCrop"
        android:src="@drawable/face_woman_smile" />

    <ImageView
        android:id="@+id/invitation_avatar_view_1"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:src="@drawable/face_woman_smile"
        android:scaleType="center"
        android:layout_margin="1dp" />

</LinearLayout>

我认为您需要将其添加到您的 ImageView

android:adjustViewBounds="true"

使用:

android:scaleType="fitXY"

如您所述,我通常使用 android:width="match_parent"android:height="wrap_content",但我的 ImageView 布局使用 android:scaleType

您可以阅读更多相关信息 here

在保持宽高比的同时使图像拉伸到父级的宽度

设置

1- android:layout_widthmatch_parent

2- layout_heightwrap_content

3- adjustViewBoundstrue

像这样:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:src="@drawable/unknown"
    android:adjustViewBounds="true" />

注意:这可能无法在预览中正确呈现,但可以在运行时运行。