【问题标题】:Why do I get white space on top and on the bottom of my ImageView in my RelativeLayout?为什么我的 RelativeLayout 中 ImageView 的顶部和底部都有空白?
【发布时间】:2020-05-13 14:56:39
【问题描述】:

我正在使用相对布局来覆盖图像。到目前为止,在我测试过的所有屏幕尺寸(从 2.7 到 10.1 英寸)上,我总是在图像顶部出现空白。在我的 IDE 中,我总是看到我的 relativelayout 导致图像顶部和底部的额外空间。

这是为什么呢?我已将所有高度属性设置为wrap_content,甚至添加了adjustViewBounds 属性。

注意:您应该知道我的图像尺寸要大得多,这意味着会有某种缩放。

感谢您的提示!

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical" >

<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical" 
    android:focusable="true"
android:focusableInTouchMode="true">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="@string/bgf"
    android:textColor="#000000"
    android:textSize="25sp" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:adjustViewBounds="true"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:paddingBottom="5dp"
        android:layout_gravity="center_horizontal"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/cde"
        android:contentDescription="@string/cde" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:layout_gravity="center_horizontal"
        android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
        android:src="@drawable/fgh"
        android:contentDescription="@string/abc" />

</RelativeLayout>


</LinearLayout>
</ScrollView>

【问题讨论】:

    标签: android android-linearlayout android-relativelayout


    【解决方案1】:

    我遇到了确切的问题。苦苦挣扎了好久,通过关注this解决了

    并将以下内容添加到我的程序中

     android:adjustViewBounds="true"
    

    效果很好

    【讨论】:

      【解决方案2】:

      当图像被缩小以适应可用区域而不会丢失图像的纵横比时,就会发生这种情况。你得到了空白,因为图像首先占据了可用宽度,并且根据原始图像的纵横比降低了高度。

      为了更清楚地了解,我建议您执行以下操作:

      • 将相对布局的背景颜色设置为某种颜色

      现在你可以理解 imageView 和 relativelayout 之间的空间了。

      在您的设备上检查后,请执行以下更改并重试

      • 在您的 imageView 中设置属性 scaleType = "fitXY"。

      这将使图像缩放并占据 imageView 可用的完整区域。 (在这种情况下,原始图像的纵横比将丢失)。现在你就会知道 imageView 占用的面积了。

      我想一旦你这样做了,你就可以得出结论:

      1. 在第一次运行时如果你将relativeLayout的背景设置为黑色,因为imageView占据了整个区域,所以不可见。

      2. 在第二次运行中,图像将覆盖整个高度和宽度,尽管纵横比丢失了。因此,这可以确定 imageView 确实覆盖了宽度和高度并且没有剩余空间,这是图像的纵横比,即问题

      如果您得到完全不同的结果,请告知,我们可以解决

      编辑:

      请务必删除您为 imageView 提供的填充

      【讨论】: