【问题标题】:How to make image fill RelativeLayout background without stretching如何使图像填充RelativeLayout背景而不拉伸
【发布时间】:2012-06-30 16:54:53
【问题描述】:

在我的 Android 项目中,我不太确定如何让我的背景图像填满 XML 中的整个 RelativeLayout 根元素,即屏幕大小。我想确保这适用于所有纵横比,因此图像将根据需要垂直或水平剪辑。有人知道如何轻松做到这一点吗?我只看到过关于ImageViews 和Buttons 的问题,但不是很笼统的Views。

我目前的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/enclosing_rl"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    android:fitsSystemWindows="false">
<!-- Other elements -->
</RelativeLayout>

【问题讨论】:

    标签: android background android-relativelayout


    【解决方案1】:

    除了将您的图像变成九个补丁之外,我认为这是不可能的。你可以做的是-

    1. 添加ImageView 作为RelativeLayout 中的第一个视图。
    2. layout_centerInParent 设置为true
    3. layout_widthlayout_height 设置为match_parent
    4. 然后将scaleType 设置为centerCrop

    这将确保图像填满屏幕而不会出现任何失真,但根据屏幕尺寸/方向,图像的顶部/底部或左/右部分可能会被截断。

    <ImageView 
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop"
                android:src="@drawable/background" />
    

    RelativeLayout 中的任何其他视图都将出现在 ImageView 的顶部,只要它是 RelativeLayout 中的第一个视图(当您在 xml 中时)。

    【讨论】:

      【解决方案2】:

      在您的 res/drawable 文件夹中创建一个位图可绘制 XML 资源:

      <?xml version="1.0" encoding="utf-8"?>
      <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
          android:src="@drawable/background"
          android:tileMode="repeat" />
      

      使用该drawable作为背景而不是@drawable/background

      【讨论】:

        【解决方案3】:

        根据这个answer如果你想要你的ImageView填写你的RelativeLayout,使用align参数ImageView

        您可以将所有视图放入LinearLayout 并将align 参数设置为您的背景ImageView

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
        
             <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/my_background"
                android:scaleType="centerCrop"
                android:layout_alignTop="@+id/my_views"
                android:layout_alignBottom="@+id/my_views"
        
                />
        
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/my_views"
                android:orientation="vertical" >
            <!-- stuff -->
            </LinearLayout>
        
        
        </RelativeLayout>
        

        【讨论】:

          【解决方案4】:

          其聪明且 100% 有效的答案是设置图像视图的属性 scaleType !

           android:scaleType="fitCenter"
          

          【讨论】: