How to convert a Drawable to a Bitmap?

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

    Here is the nice Kotlin version of the answer provided by @Chris.Jenkins here: https://stackoverflow.com/a/27543712/1016462

    fun Drawable.toBitmap(): Bitmap {
      if (this is BitmapDrawable) {
        return bitmap
      }
    
      val width = if (bounds.isEmpty) intrinsicWidth else bounds.width()
      val height = if (bounds.isEmpty) intrinsicHeight else bounds.height()
    
      return Bitmap.createBitmap(width.nonZero(), height.nonZero(), Bitmap.Config.ARGB_8888).also {
        val canvas = Canvas(it)
        setBounds(0, 0, canvas.width, canvas.height)
        draw(canvas)
      }
    }
    
    private fun Int.nonZero() = if (this <= 0) 1 else this
    

提交回复
热议问题