每日博客

Android 中 Bitmap 和 Drawable 相互转换的方法

Drawable 转换成 Bitmap

1.通过 BitmapFactory 中的 decodeResource 方法,将资源文件中的 R.drawable.ic_drawable 转化成Bitmap

Resources res = getResources();
Bitmap    bmp = BitmapFactory.decodeResource(res, R.drawable.ic_drawable);

2.将 Drable 对象先转化成 BitmapDrawable ,然后调用 getBitmap 方法 获取

Resource res      = gerResource();
Drawable drawable = res.getDrawable(R.drawable.ic_drawable);//获取drawable
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bm         = bd.getBitmap();

3.根据已有的Drawable创建一个新的Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {

        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        System.out.println("Drawable转Bitmap");
        Bitmap.Config config =
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        //注意,下面三行代码要用到,否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);

        return bitmap;
    }

Bitmap 转换成 Drawable

Drawable drawable = new BitmapDrawable(bmp);
posted @ 2021-05-22 20:41  谦寻  阅读(30)  评论(0编辑  收藏  举报