Android布局 - 在xml中偏移背景图片

3

我希望使用一张较大的PNG图片作为不同布局的背景,但是需要对其进行偏移,以便呈现不同的部分(类似于CSS中的做法),最好在XML中实现。

我的活动主布局包含以下XML代码:

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@layout/bg1">

布局bg1由以下xml组成:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/big_image"
android:layout_marginTop="50sp"
android:paddingTop="50sp"
android:gravity="top|left" />

gravity属性按预期工作,但是边距和填充被忽略了,可能是因为我在位图对象上工作而不是布局上。我想做的是将它们设置为负值,以便仅显示部分图片。我尝试使用形状,但那只包装内容,我需要填充整个背景。

如果您有任何建议,将不胜感激。谢谢。


使用以下代码解决问题,确保ImageView位于XML文件的顶部,这样它就在所有其他控件的后面: <ImageView android:id="@+id/bigLogo" android:src="@drawable/big_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="-90px" /> - Dan Kilpatrick
2个回答

5

我使用了一个带有负上边距值的ImageView。在布局中,首先声明ImageView,以便它位于控件堆栈的最下方,并在其他控件之后呈现。

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/bigLogo"
        android:src="@drawable/big_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"    
        android:layout_marginTop="-100px" />
</RelativeLayout>

2
您可以使用InsetDrawable(它可以在XML中使用)为另一个drawable添加额外的填充。

1
我已经更改了原始帖子中bg1.xml的布局,使用了一个inset并设置了insetTop。然而,整个布局的内容都是inset,而不仅仅是背景可绘制部分。我原本期望背景会像网页上的“水印”一样处理,但惊讶于主要内容也受到影响。也许我应该使用一个定位的ImageView代替? - Dan Kilpatrick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接