在Android中将位图转换为可绘制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23107090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting bitmap to drawable in Android
提问by user3522370
I'm downloading the image from server and storing it in bitmap object. I want to set this image as background for button. But the button doesn't have the property setImageBitmap. So is there anyway I can set the background of button with the downloaded bitmap image? Like by converting the bitmap to drawable? Sorry, I'm new to Android, please bear with my mistakes (if any).
我正在从服务器下载图像并将其存储在位图对象中。我想将此图像设置为按钮的背景。但是按钮没有 setImageBitmap 属性。那么无论如何我可以使用下载的位图图像设置按钮的背景?喜欢通过将位图转换为可绘制?抱歉,我是 Android 新手,请原谅我的错误(如果有的话)。
P.S : I want to use button control only. Because I want some text at the bottom of each buttons and I'm creating these buttons dynamically.
PS:我只想使用按钮控制。因为我想在每个按钮的底部添加一些文本,并且我正在动态创建这些按钮。
回答by Spring Breaker
The best way to convert a Bitmap
to drawable in android is as follows,
Bitmap
在android中将a转换为drawable的最佳方法如下,
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
where bitmap
is the name the Bitmap
. Then set the drawable as your Button
background as follows,
bitmap
的名字在哪里Bitmap
。然后将 drawable 设置为您的Button
背景,如下所示,
btn.setBackground(drawable);
N.B:Without specifying getResources()
as the first argument, you may experience inconsistent image sizing across different screen densities.
注意:如果不指定getResources()
第一个参数,您可能会遇到不同屏幕密度下图像大小不一致的情况。
for more info refer this http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html
有关更多信息,请参阅此 http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html
回答by ryderz8
回答by AndyN
Convert Bitmap
to BitmapDrawable
like this
转换Bitmap
成BitmapDrawable
这样
Drawable drawable = new BitmapDrawable(getResources(),your_bitmap);
and then set it as background to button as ,
然后将其设置为背景按钮为,
button.setBackgroundDrawable(drawable);
P.S.You can also do the same inline as ,
PS你也可以做同样的内联,
button.setBackgroundDrawable(new BitmapDrawable(getResources(),your_bitmap));
回答by Minixuru
This is how to do it, I've used several times:
这是如何做到的,我已经使用过多次:
Drawable drawable = (Drawable)new BitmapDrawable(Bitmap);
Button button= new Button(this);
button.setBackground(drawable);