在LinearLayout中缩放背景图像

14

我遇到了以下问题:

我有一个LinearLayout,在其中放置了一个ScrollView,ScrollView中包含一些自定义视图。现在我想将一张图片放在LinearLayout的背景中,并保持图片的原始尺寸。但是当我设置LinearLayout的背景属性时,它会被拉伸以适应整个屏幕。我该如何使图片保持其原始大小?

我的xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/root"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/some_drawable">
  <ScrollView
    android:id="@+id/scrollview"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:fillViewport="true">
    <some.custom.layout
        android:id="@+id/mainLayout"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        />
  </ScrollView>
</LinearLayout>

看到有些人不时地点赞这个问题(感谢!),但我想在这里声明一下,这个问题现在已经有9年了,在Android世界中发生了很多事情。现在很可能有更好的方法来解决这个问题! - Joris
5个回答

28

Egor的回答的代码示例:

<FrameLayout
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    >

    <ImageView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/background"
        />

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

    </LinearLayout>

</FrameLayout>

21

尝试使用FrameLayout,其中包含一个ImageView和LinearLayout。例如,尝试更改图像的alpha值,并将其移动到FrameLayout的前景中,从而使LinearLayout保持在背景中。希望这可以帮到您!


2
这个方法很有效,但我认为有一个更加优雅的解决方案在这里可以找到:https://dev59.com/5XE85IYBdhLWcg3wbS5h - iganev

3
<RelativeLayout
    android:id="@+id/relLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/layoutLogin"
        android:layout_alignLeft="@id/layoutLogin"
        android:layout_alignRight="@id/layoutLogin"
        android:layout_alignTop="@+id/layoutLogin"
        android:adjustViewBounds="true"
        android:background="@mipmap/ic_photo_bg"
        android:scaleType="fitXY" />

    <LinearLayout
        android:id="@+id/layoutLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    </LinearLayout>

</RelativeLayout>

1

除了ColdForged的建议,你也可以从LinearLayout转换到RelativeLayout,并使用ImageView来显示图像,而不是将背景更改为它。在RelativeLayout中,视图可以相互干扰,而不像在LinearLayout中。


我已经尝试过这个,但是如何将ScrollView的内容绘制在ImageView上,使得图片成为背景呢? - Joris
1
也许通过为滚动视图的背景设置alpha值 - ernazm

0
你可以看一下InsetDrawable。或者你可能需要子类化你的布局来绘制你想要的背景元素,因为背景元素没有你需要的功能。

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