I would like to set a certain Drawable
as the device\'s wallpaper, but all wallpaper functions accept Bitmap
s only. I cannot use WallpaperMan
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