Android常用的Drawable和Bitmap之间的转化方法

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



 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值