在代码中获取资源文件下图片:
方法1:
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ic );
方法2:
Drawable drawable = getResources().getDrawable(R.drawable.ic);
方法3:
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的子类,可以直接使用;