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

Android中图片资源加载方式
本文介绍了在Android应用开发中加载图片资源的多种方法,包括直接通过资源ID加载、使用BitmapFactory从文件路径加载等,并提供了Bitmap与Drawable相互转换的具体实现。

在代码中获取资源文件下图片:

方法1:

Bitmap  bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ic );

方法2:

Drawable drawable = getResources().getDrawable(R.drawable.ic);

方法3:

iv.setImageResource(R.drawable.ic_launcher);


获取路径下的图片资源:

  1. 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();

第二种:

  1. 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的子类,可以直接使用;






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值