How to convert a Drawable to a Bitmap?

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

    The latest androidx core library (androidx.core:core-ktx:1.2.0) now has an extension function: Drawable.toBitmap(...) to convert a Drawable to a Bitmap.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-21 23:02

    Android provides a non straight foward solution: BitmapDrawable. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic to the a BitmapDrawable and then cast it to a Bitmap.

    Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
    
    0 讨论(0)
  • 2020-11-21 23:02

    if you are using kotlin the use below code. it'll work

    // for using image path

    val image = Drawable.createFromPath(path)
    val bitmap = (image as BitmapDrawable).bitmap
    
    0 讨论(0)
  • 2020-11-21 23:05

    very simple

    Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
    
    0 讨论(0)
  • 2020-11-21 23:06

    BitmapFactory.decodeResource() automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap source = BitmapFactory.decodeResource(context.getResources(),
                                                 R.drawable.resource_name, options);
    

    or

    InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
    bitmap = BitmapFactory.decodeStream(is);
    
    0 讨论(0)
提交回复
热议问题