背景图像放置

时间:2010-05-06 13:41:49

标签: android background-image android-layout

我正在尝试将我的根LinearLayout元素(在两个维度中设置为fill_parent)设置为背景图像,无论设备的方向如何,该背景图像始终位于屏幕的左下角。如果有某种方法可以设置背景图像位置,例如使用“background-position:left bottom;”可以使用css执行的操作,这将是非常好的。但我没有看到在Android中实现这一目标的方法。有没有办法做到这一点?

感谢您的帮助。

4 个答案:

答案 0 :(得分:81)

您必须使用XML文件中的位图创建自定义位图drawable(例如“res / drawables / my_drawable.xml”

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/my_png_file"
    android:gravity="bottom|left" />

然后将此drawable xml设置为视图的背景(“@ drawables / my_drawable”)。 然而,Android网站中的可绘制XML格式记录很少,因此找出如何自行解决问题绝对不是一个容易的问题。

答案 1 :(得分:9)

如果找到以编程方式执行此操作的优势:图像适合布局而不是更大。没有想法为什么。

代码:

Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setGravity(Gravity.BOTTOM|Gravity.RIGHT);
LinearLayout layout = (LinearLayout) findViewById(R.id.background_root);
layout.setBackgroundDrawable(bitmapDrawable);

答案 2 :(得分:0)

将LinearLayout包装到RelativeLayout并向其添加ImageView。使用android:layout_alignParentBottom和android:layout_alignParentLeft,您可以将图像放在左下角。

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:src="@drawable/my_image" />

    <LinearLayout
        android:id="@+id/linearLayout"
        ... >

确保ImageView是RelativeLayout的第一个在背景中绘制图像的元素。

答案 3 :(得分:0)

我的回答只是上述答案的更新 如果您使用XML作为背景,则可能会出现宽高比问题

所以请使用此代码

Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
  bitmapDrawable.setGravity(Gravity.BOTTOM| Gravity.RIGHT| Gravity.FILL_HORIZONTAL);
LinearLayout layout = (LinearLayout) findViewById(R.id.background_root);
layout.setBackgroundDrawable(bitmapDrawable);

Gravity.Fill_HORIZONTAL将适合您应用背景的布局宽度,您也可以在XML文件中提及,但正如我所说,它会出现Image Ratio的问题

相关问题