我有一個RelativeLayout
對象,並且想用動態創建的Bitmap對象動態更改背景圖像(它動態地更改其顏色)。如何使用具有位圖的relativelayout.setBackgroundDrawable()?
我看到,當我想更新RelativeLayout
對象的背景圖像時,我只能選擇setBackgroundDrawable()
,它需要一個Drawable對象作爲參數。
我的問題是,我該如何將動態創建的Bitmap對象轉換爲Drawable對象?
我有一個RelativeLayout
對象,並且想用動態創建的Bitmap對象動態更改背景圖像(它動態地更改其顏色)。如何使用具有位圖的relativelayout.setBackgroundDrawable()?
我看到,當我想更新RelativeLayout
對象的背景圖像時,我只能選擇setBackgroundDrawable()
,它需要一個Drawable對象作爲參數。
我的問題是,我該如何將動態創建的Bitmap對象轉換爲Drawable對象?
BitmapDrawable(obj)
轉換位圖對象爲繪製對象。
嘗試:
RelativeLayout relative = (RelativeLayout) findViewById(R.id.relative1);
Drawable dr = new BitmapDrawable(bit);
(view).setBackgroundDrawable(drawable);
我希望這會幫助你。
不推薦使用新的BitmapDrawable(位圖);使用新的BitmapDrawable(getResources(),位圖) –
此答案在3年之前給出。因此,隨着新方法的出現,它可能會獲得最高的棄用舊方法的機會。那時候是對的。 – Siten
試試這個,
Drawable drawable = new BitmapDrawable(bitmap);
Drawable d = new BitmapDrawable(bitmap);
您可以通過這種方式做到這一點
Drawable drawable = new BitmapDrawable(bitmap);
RelativeLayout r;
r = (RelativeLayout) findViewById(R.id.relativelayout1);
ll.setBackgroundDrawable(drawable);
RelativeLayout rl=(RelativeLayout) findViewById(R.id.main1);
Bitmap myImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Drawable dr = new BitmapDrawable(myImage);
rl.setBackgroundDrawable(dr);
//爲RelativeLayout的創建參考
RelativeLayout layout = (RelativeLayout) findViewById(R.id.rl);
//使用以下方法來設置背景佈局參考
Drawable drawable = getResources().getDrawable(R.drawable.bg);
layout.setBackground(drawable);
注: R.id.rl是ID RelativeLayout
R.drawable.bg id drawabl中的圖像e文件夾
您的圖片是來自本地的來源或網址? –