1.简介:
在Android程序开发中,经常需要处理图像,有时,需要将Drawable对象转换为Bitmap对象进行处理,本篇介绍两种方式,实现“通过Drawable对象获取Bitmap对象”的目的。
2. 方式一:通过BitmapDrawable函数进行获取:
//获取
public Bitmap drawableToBitamp(Drawable drawable)
{
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bitmap = bd.getBitmap();
return bitmap
}
说明:
先将Drawable对象转换为
BitmapDrawable对象,再通过getBitmap来获取Bitmap对象。
3. 方式二:通过Bitmap.createBitmap来创建一个新的Bitmap对象:
public Bitmap drawableToBitamp(Drawable drawable)
{
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
System.out.println("Drawable转Bitmap");
//设置参数
Bitmap.Config config =
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
//创建bitmap对象
Bitmap bitmap = Bitmap.createBitmap(w,h,config);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
说明:
通过Bitmap.Config设置bitmap对象的参数,再通过调用Bitmap.createBitmap来创建bitmap,这种方式经常被使用。