Bitmap与Drawable间的关系

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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值