如何使图像填充RelativeLayout背景而不拉伸 [英] How to make image fill RelativeLayout background without stretching

查看:48
本文介绍了如何使图像填充RelativeLayout背景而不拉伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ImageViews and Buttons, but not really generic Views.

我目前的 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-

  1. 添加一个 ImageView 作为 RelativeLayout 中的第一个视图.
  2. layout_centerInParent 设置为 true.
  3. layout_widthlayout_height 设置为 match_parent.
  4. 然后将 scaleType 设置为 centerCrop.
  1. Add an ImageView as the first view in your RelativeLayout.
  2. Set layout_centerInParent to true.
  3. Have the layout_width and layout_height set to match_parent.
  4. Then set scaleType to centerCrop.

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

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背景而不拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆