问题描述
在我的 Android 项目中,我不太确定如何让我的背景图像填充 XML 中的整个 RelativeLayout
根元素,即屏幕大小.我想确保这适用于所有纵横比,因此图像将根据需要垂直或水平剪辑.有人知道如何轻松做到这一点吗?我只看到有关 ImageView
s 和 Button
s 的问题,但不是真正通用的 View
s.
In my Android project, I am not quite sure how to make my background image fill the entirety of the RelativeLayout
root element in XML, which is the size of the screen. I want to be sure that this works for all aspect ratios, so the image will clip vertically or horizontally as necessary. Does someone know how to do this easily? I've only seen questions regarding ImageView
s and Button
s, but not really generic View
s.
我目前的 XML 文件:
My XML file currently:
<?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>
推荐答案
除了把你的图片变成九个补丁之外,我认为这是不可能的.你可以做的是-
Other than turning your image into a nine patch I don't think this is possible. What you could do instead is-
- 添加一个
ImageView
作为RelativeLayout
中的第一个视图. - 将
layout_centerInParent
设置为true
. - 将
layout_width
和layout_height
设置为match_parent
. - 然后将
scaleType
设置为centerCrop
.
- Add an
ImageView
as the first view in yourRelativeLayout
. - Set
layout_centerInParent
totrue
. - Have the
layout_width
andlayout_height
set tomatch_parent
. - Then set
scaleType
tocenterCrop
.
这将确保图像填满屏幕而不会出现任何失真,但根据屏幕尺寸/方向,图像的顶部/底部或左/右部分可能会被截断.
That will make sure the image fills the screen without any distortion, but depending on screen size/orientation either some of the top/bottom or left/right of the image may be cut off.
<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 中时).
Any other views in the RelativeLayout
will appear on top of the ImageView
, as long as it is the first view in the RelativeLayout
(when you are in the xml).
这篇关于如何使图像填充RelativeLayout背景而不拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!