How to convert a Drawable to a Bitmap?

前端 未结 20 2502
攒了一身酷
攒了一身酷 2020-11-21 22:46

I would like to set a certain Drawable as the device\'s wallpaper, but all wallpaper functions accept Bitmaps only. I cannot use WallpaperMan

20条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:09

    A Drawable can be drawn onto a Canvas, and a Canvas can be backed by a Bitmap:

    (Updated to handle a quick conversion for BitmapDrawables and to ensure that the Bitmap created has a valid size)

    public static Bitmap drawableToBitmap (Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable)drawable).getBitmap();
        }
    
        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;
    
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap); 
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
    
        return bitmap;
    }
    

提交回复
热议问题