How to convert a Drawable to a Bitmap?

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

    METHOD 1 : Either you can directly convert to bitmap like this

    Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
    

    METHOD 2 : You can even convert the resource into the drawable and from that you can get bitmap like this

    Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();
    

    For API > 22 getDrawable method moved to the ResourcesCompat class so for that you do something like this

    Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();
    

提交回复
热议问题