Bitmap
- 称作位图,一般位图的文件格式后缀为bmp
Drawable
- 作为Android平下通用的图形对象,它可以装载常用格式的图像
比如GIF、PNG、JPG,当然也支持BMP,当然还提供一些高级的可视化对象,比如渐变、图形等。
Bitmap是Drawable . Drawable不一定是Bitmap
Drawable在内存占用和绘制速度这两个非常关键的点上胜过Bitmap
1、Bitmap对象
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.icon);
获取其宽高的方法:
bmp.getHeight()
bmp.getWidth()
2、Drawable对象
Drawable drawable = getResources().getDrawable(R.drawable.icon);
获取其宽高的方法:
drawable.getIntrinsicWidth();
drawable.getIntrinsicHeight();
3、Bitmap转换成Drawable
Bitmap bm=xxx; //xxx根据你的情况获取
BitmapDrawable bd= new BitmapDrawable(getResource(), bm);
//因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
4、Drawable转化为Bitmap
转化的方式是把Brawable通过画板画出来
public static Bitmap drawableToBitmap(Drawable drawable) {
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}
5、Bitmap → byte[]
public byte[] BitmapToByte(Bitmap bmp) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, b);
return b.toByteArray();
}
6、byte[] → Bitmap
public Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
部分转载学习自:
http://dyh7077063.iteye.com/blog/970672