How to convert a Drawable to a Bitmap?

前端 未结 20 2480
攒了一身酷
攒了一身酷 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:25

    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);

    This will not work every time for example if your drawable is layer list drawable then it gives a null response, so as an alternative you need to draw your drawable into canvas then save as bitmap, please refer below a cup of code.

    public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
            FileOutputStream fOut = new FileOutputStream(file);
            Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
            if (drw != null) {
                convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
        Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, widthPixels, heightPixels);
        drawable.draw(canvas);
        return bitmap;
    }
    

    above code save you're drawable as drawable.png in the download directory

提交回复
热议问题