android - ImageView 填充 parent 的宽度或高度,但保持纵横比

标签 android android-layout android-imageview android-relativelayout

我有一个方形图像(虽然这个问题也适用于矩形图像)。我想尽可能大地显示图像,必要时拉伸(stretch)它们以填充它们的 parent ,同时仍然保持纵横比。图像小于 ImageView。问题是,我无法拉伸(stretch)图像并“匹配”ImageView 的高度和宽度。

这是我的 XML 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp">

    <ImageView android:id="@+id/image"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:adjustViewBounds="true"
               android:scaleType="fitCenter"
               android:layout_marginTop="10dp"/>

    <TextView android:id="@+id/name"
              android:layout_below="@id/image"
              android:layout_alignLeft="@id/image"
              android:layout_marginTop="20dp"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textSize="18dp"/>

    <TextView android:id="@+id/name2"
              android:layout_below="@id/name"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textSize="14dp"/>


</RelativeLayout>

我使用了许多 fill_parentwrap_content 与多个 scaleTypes 的组合:fitCenterfitStartfitEndcenterInside,它们都以正确的纵横比绘制图像,但它们都没有真正放大图像和 ImageView 本身,导致无论是 TextViews 一直被推离屏幕、ImageView 内的空白区域、图像未缩放或图像被裁剪。

我无法确定正确的组合。

最佳答案

这些:

android:layout_height="wrap_content"
android:scaleType="fitStart"
android:adjustViewBounds="true"

应调整图像大小并更改边界大小以适应新图像大小。如果它没有在您的设备上执行此操作,请发布您正在使用的图像以及您正在测试的设备。

关于android - ImageView 填充 parent 的宽度或高度,但保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10826422/

相关文章:

android - 将我的 RelativeLayout 放在 ScrollView 中会错放布局中的所有项目

java - android.view.InflateException : Binary XML file line #0: Error inflating class <unknown> in recyclerview for below API 21

Android - 如何将 Imageview 中的图像上传到远程服务器?

java - Android MediaMetaDataReceiver.setDataSource 上的 IllegalArgumentException

android - 在 QRcodeScanner React Native 中打开/关闭手电筒 - 替代解决方案

android - 是否可以将两个(正在积极开发的)Android 应用程序模块合并到同一个 Android Studio 项目中?

android - 如何将 View 置于屏幕外?

android - 如何在不使用 "setImageBitmap()"的情况下加载带有 png 文件的 ImageView?

android - 如何在 CardView 的底部显示 ImageView

android - 应用程序未在模拟器中显示