IT源码网

Drawable转换为Bitmap两种方法

wyy 2021年04月03日 程序员 411 0

如果通过网络加载了一张位图,想拿到这张位图的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(); 
    }

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!