如何使用RelativeLayout.setBackgroundDrawable()方法设置位图背景?

10
我有一个 RelativeLayout 对象,想要动态地将背景图片改为动态创建的 Bitmap 对象(它会动态更改颜色)。
我发现当我想要更新 RelativeLayout 对象的背景图片时,只能选择需要 Drawable 对象作为参数的 setBackgroundDrawable() 方法。
我的问题是,如何将动态创建的 Bitmap 对象转换为 Drawable 对象?

您的图片是来自本地源还是URL? - Nikunj Patel
6个回答

21

BitmapDrawable(obj) 将 Bitmap 对象转换为 Drawable 对象。

尝试:

RelativeLayout relative = (RelativeLayout) findViewById(R.id.relative1);
Drawable dr = new BitmapDrawable(bit);
(view).setBackgroundDrawable(drawable);

希望这能对你有所帮助。


1
新的BitmapDrawable(bitmap)已经被弃用,请使用new BitmapDrawable(getResources(), bitmap)。 - Laurens Koppenol
这个答案是三年前给出的。因此,随着新方法的出现,它可能会有更高的几率淘汰旧方法。当时它是正确的。 - Siten

6
你可以通过这种方式来完成。
Drawable drawable = new BitmapDrawable(bitmap);
RelativeLayout r;
r = (RelativeLayout) findViewById(R.id.relativelayout1);
ll.setBackgroundDrawable(drawable);

3
试试这个:
Drawable drawable = new BitmapDrawable(bitmap);

2
RelativeLayout rl=(RelativeLayout) findViewById(R.id.main1);
Bitmap myImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Drawable dr = new BitmapDrawable(myImage);
rl.setBackgroundDrawable(dr);

1
Drawable d = new BitmapDrawable(bitmap);

0

//创建RelativeLayout的引用

RelativeLayout layout = (RelativeLayout) findViewById(R.id.rl);

//使用以下方法将背景设置为布局引用

Drawable drawable = getResources().getDrawable(R.drawable.bg);
layout.setBackground(drawable);

注意: R.id.rl 是RelativeLayout的ID。

R.drawable.bg是drawable文件夹中的图像。


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