2013-05-31 75 views
1

我從服務器下載圖像並將其設置爲背景。但我需要爲該背景圖像分配重複圖像漸變,並且我需要在其上顯示一些文本。在背景圖像上重複圖像漸變

這是我的代碼,它用於從服務器下載圖像並將其設置爲背景。

Bitmap bitmap = DownloadImage(imageUrl); 
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap); 
bitmapDrawable.setGravity(Gravity.BOTTOM|Gravity.RIGHT); 
//Drawable d = new BitmapDrawable(bitmap); 
myLinearLayout.setBackgroundDrawable(bitmapDrawable); 

我創建了一個圖層列表,我需要在背景的頂部顯示。

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
<item> 
    <shape android:shape="rectangle"> 
     <gradient 
      android:type="radial" android:gradientRadius="500" 
      android:startColor="#17568A" 
      android:endColor="#494C4F" /> 

    </shape> 
</item> 
<item> 
    <bitmap 
     android:src="@drawable/gradient_dish" 
     android:tileMode="repeat" /> 
</item> 
</layer-list>   

但我已經分配服務器映像佈局背景,所以不能在後臺分配這個XML文件。

我有一個圖像「gradient_dish」,我想重複,並希望與背景圖像顯示。

我怎樣才能做到這一點?請給我提供一些參考或鏈接。
在此先感謝...

+0

不能只需在代碼從'BitmapDrawable'獲取從web +層創建'LayerDrawable'從您發佈的xml drawable中使用它作爲背景? – Luksprog

+0

你有這方面的任何參考代碼嗎? –

+1

看看這個https://gist.github.com/luksprog/5696975 – Luksprog

回答

2

使用從網絡中檢索到的圖像,您可以構建所需的可繪製對象,還可以從您發佈的xml文件添加可繪製對象。你可以使用下面的方法:

public Drawable createBackground(Bitmap bitmap) { 
    Drawable[] layers = new Drawable[3]; 
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap); 
    bitmapDrawable.setGravity(Gravity.BOTTOM | Gravity.RIGHT); 
    layers[0] = bitmapDrawable; 
    GradientDrawable gd = new GradientDrawable(); 
    gd.setShape(GradientDrawable.RECTANGLE); 
    gd.setGradientRadius(500); 
    gd.setGradientType(GradientDrawable.RADIAL_GRADIENT); 
    gd.setColors(new int[] { Color.parseColor("#17568A"), 
      Color.parseColor("#494C4F") }); 
    layers[1] = gd; 
    BitmapDrawable lastBitmapDrawable = (BitmapDrawable) getResources() 
      .getDrawable(R.id.gradient_dish); 
    lastBitmapDrawable.setTileModeX(TileMode.REPEAT); 
    layers[2] = lastBitmapDrawable; 
    LayerDrawable bck = new LayerDrawable(layers); 
    return bck; 
} 

,那麼只需在做:

Bitmap bitmap = DownloadImage(imageUrl); 
myLinearLayout.setBackgroundDrawable(createBackground(bitmap)); 
+0

你能幫一個忙嗎?它在模擬器上工作,但不在真實設備上......怎麼樣?謝謝... –

+0

@SandipArmalPatil它不工作在哪種方式(是不完整的,圖像沒有出現)?另外,你在哪個設備上測試過它,以及什麼api級別(你是否嘗試過在其他設備上測試過)? – Luksprog

0

爲什麼不將圖像作爲背景圖像放置到跨越整個屏幕的簡單視圖中,然後將其餘佈局放在該圖像的頂部並使您的漸變半透明(即從不透明的顏色開始,轉到半透明或完全透明的顏色)。 通過這種方式,圖像將根據需要通過真實照射。