I tried to convert a drawable resource to a bitmap but every code snippet and every own try returned null or an empty string.
I tried it with basic approaches like Bitmapfactory.decodeResource (Here i tried it with activity context, application context etc. and with every kind of drawable resource (png, vector, xml) and i tried different code snippets from convertion and it always returns null or "". I tried to change the drawable folders also instead of drawable-24 i tried the basic drawable folder.
BitmapFactory.decodeResource(applicationContext.resources,
R.drawable.test)
BitmapFactory.decodeResource(this.resources,
R.drawable.test)
BitmapFactory.decodeResource(resources,
R.mipmap.ic_launcher)
fun drawableToBitmap(drawable: Drawable): Bitmap {
var bitmap: Bitmap? = null
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <=
0) {
bitmap =
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap!!)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
///////////
fun drawableToBitmap(drawable: Drawable): Bitmap {
var bitmap: Bitmap? = null
if (drawable is BitmapDrawable) {
val bitmapDrawable = drawable as BitmapDrawable
if (bitmapDrawable.bitmap != null) {
return bitmapDrawable.bitmap
}
}
bitmap = if (drawable.intrinsicWidth <= 0 ||
drawable.intrinsicHeight <= 0) {
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
} else {
Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
}
val canvas = Canvas(bitmap!!)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
试试这个(上下文是您的活动上下文或其他)
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.