如何将Drawable转为Bitmap?
本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术。本文将讲解如何将Drawable转为Bitmap?
我想要设置某个Drawable作为墙纸,但是所有的墙纸功能只支持Bitmap。因为我是pre 2.1系统,所以不能使用WallpaperManager。
而且,我从网上下载的图片在R.drawable中也不能使用,出现这种情况该怎么处理?
(最佳答案)
这种方法可以将BitmapDrawable转换成Bitmap
1
2
|
Drawable
d = ImagesArrayList.get(0); Bitmap
bitmap = ((BitmapDrawable)d).getBitmap(); |
通常情况下,我觉得下面代码比较有用:
1
2
|
Bitmap
icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_resource); |
注:下面介绍一种可以下载图片的版本:
1
2
3
4
5
6
7
8
|
String
name = c.getString(str_url); URL
url_value = new
URL(name); ImageView
profile = (ImageView)v.findViewById(R.id.vdo_icon); if
(profile != null )
{ Bitmap
mIcon1 = BitmapFactory.decodeStream(url_value.openConnection().getInputStream()); profile.setImageBitmap(mIcon1); } |
1
2
3
4
5
6
7
8
9
10
11
12
|
public
static Bitmap drawableToBitmap (Drawable drawable) { if
(drawable instanceof
BitmapDrawable) { return
((BitmapDrawable)drawable).getBitmap(); } Bitmap
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas
canvas = new
Canvas(bitmap); drawable.setBounds(0,
0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return
bitmap; } |
Drawable可以放在Canvas上,而Bitmap支持Canvas:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
static Bitmap drawableToBitmap (Drawable drawable) { if
(drawable instanceof
BitmapDrawable) { return
((BitmapDrawable)drawable).getBitmap(); } int
width = drawable.getIntrinsicWidth(); width
= width > 0 ? width : 1; int
height = drawable.getIntrinsicHeight(); height
= height > 0 ? height : 1; Bitmap
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas
canvas = new
Canvas(bitmap); drawable.setBounds(0,
0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return
bitmap; } |
原文链接:http://stackoverflow.com/questions/3035692/how-to-convert-a-drawable-to-a-bitmap
文章选自StackOverFlow社区,鉴于其内容对于开发者有所帮助,现将文章翻译于此,供大家参考及学习。9Tech将每日持续更新,读者可点击StackOverflow(简称:SOF)精选问答汇总,查看全部译文内容。同时,我们也招募志同道合的技术朋友共同翻译,造福大家!报名请发邮件至zhangqi_wj@cyou-inc.com。