如何使图像填充RelativeLayout背景而不拉伸

pqn*_*pqn 22 android background android-relativelayout

在我的Android项目中,我不太清楚如何使我的背景图像填充RelativeLayoutXML中的整个根元素,这是屏幕的大小.我想确保这适用于所有宽高比,因此图像将根据需要垂直或水平剪裁.有人知道如何轻松地做到这一点吗?我只看过有关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>
Run Code Online (Sandbox Code Playgroud)

Fly*_*n81 55

除了将你的图像变成九个补丁之外我不认为这是可能的.您可以做的是添加ImageView作为RelativeLayout中的第一个视图.将layout_centerInParent设置为true并将layout_width和layout_height设置为match_parent.然后将scaleType设置为centerCrop.这将确保图像填充屏幕而没有任何失真,但是根据屏幕尺寸/方向,图像的顶部/底部或左/右的一些可能被切断.

<ImageView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:scaleType="centerCrop"
            android:src="@drawable/background" />
Run Code Online (Sandbox Code Playgroud)

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


tig*_*chi 11

在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" />
Run Code Online (Sandbox Code Playgroud)

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


Ami*_*emi 6

根据这个答案如果你想ImageView填写你的RelativeLayout,请使用align参数ImageView.

您可以将所有视图添加到a 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>
Run Code Online (Sandbox Code Playgroud)