Drawable转换为Bitmap两种方法

版权声明:ThomasKwan https://blog.csdn.net/thomassamul/article/details/86649577

如果通过网络加载了一张位图,想拿到这张位图的Bitmap,有两种办法:

1,根据已有的Drawable创建一个新的Bitmap:

private Bitmap bitmap;
private void drawableToBitamp(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.createBitmap(w,h,config);
        //注意,下面三行代码要用到,否在在View或者surfaceview里的canvas.drawBitmap会看不到图
        Canvas canvas = new Canvas(bitmap);   
        drawable.setBounds(0, 0, w, h);   
        drawable.draw(canvas);
    }

2,直接从现有的Drawable中取出Bitmap:

private Bitmap bitmap;

private void drawableToBitamp(Drawable drawable)
    {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        bitmap = bd.getBitmap();
    }

猜你喜欢

转载自blog.csdn.net/thomassamul/article/details/86649577