2011-04-29 204 views
10

我遇到以下問題;在LinearLayout中縮放背景圖像

我有一個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> 

回答

20

嘗試在內部使用帶有ImageView和LinearLayout的FrameLayout。例如,嘗試更改圖像的alpha值並將其移動到FrameLayout中的前景中,因此LinearLayout保留在背景上。希望這可以幫助!

+0

這對我工作,非常感謝! – Joris 2011-05-04 08:28:14

+1

這很好,但我認爲更優雅的解決方案,可以在這裏找到:http://stackoverflow.com/questions/2781593/background-image-placement – iganev 2013-10-08 11:52:32

0

你可能需要看看InsetDrawable。無論是這樣或者它可能需要你的佈局的子類來繪製你想要的方式,因爲背景元素沒有你需要的能力。

0

除了ColdForged的建議,您可以從LinearLayout移動到RelativeLayout並使用ImageView來顯示圖像,而不是更改背景。 RelativeLayout中的意見可能會與LinearLayout不同。

+0

我已經試過這一點,但我怎麼畫了滾動的內容在圖像視圖,使得圖像的背景? – Joris 2011-04-29 15:34:29

+1

也許通過設置爲滾動視圖背景alpha的 – ernazm 2011-04-29 15:37:05

21

代碼示例葉戈爾的回答是:

<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>