bitmap和Drawable间的区别:
Bitmap - 称作位图,一般位图的文件格式后缀为bmp,当然编码器也有很多如RGB565、RGB888。作为一种逐像素的显示对象执行效率高,但是缺点也很明显存储效率低。我们理解为一种存储对象比较好。
Drawable - 作为Android平下通用的图形对象,它可以装载常用格式的图像,比如GIF、PNG、JPG,当然也支持BMP,当然还提供一些高级的可视化对象,比如渐变、图形等。
两者间的简单对比:
Drawable在内存占用和绘制速度这两个非常关键的点上胜过Bitmap;
我们经常会遇到需要在代码中获取资源文件下图片的问题:
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ic );
或者:
Drawable drawable = getResources().getDrawable(R.drawable.ic);
或者:
iv.setImageResource(R.drawable.ic_launcher);
获取路径下的图片资源:
String fileName = "/data/data/com.test/aa.png;
Bitmap bm = BitmapFactory.decodeFile(fileName);
iv.setImageBitmap(bm); //占用内存
下面来看看两者间的转换:
Drawable ----->Bitmap:
第一种:
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bm= bd.getBitmap();
第二种:
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;
}
Bitmap--------> Drawable:
第一种:
Drawable drawable = new BitmapDrawable(bitmap);
第二种:
BitmapDrawable bd= new BitmapDrawable(getResource(), bm);
BitmapDrawable是Drawable的子类,可以直接使用;
对于图片压缩和存储的知识点:
http://blog.csdn.net/jdsjlzx/article/details/44228935