You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Drawable.toBitmap返回空白Bitmap,如何极简实现Drawable转自定义尺寸Bitmap

Drawable.toBitmap()生成空白Bitmap的原因分析

出错的核心原因

  • 参数传递错误:你调用toBitmap方法时两个参数都传入了artWidth,该方法的第二个参数本应为目标高度artHeight,如果需求的目标宽高不相等,生成的Bitmap尺寸不符合预期,矢量图会被压缩、裁剪到异常区域,最终显示为空白。
  • 背景透明导致的视觉混淆:Android Core KTX提供的Drawable.toBitmap()扩展方法默认生成的Bitmap背景是全透明的,而你手动实现的代码里先绘制了一层R.color.colorPrimary的底色。你测试用的VectorDrawable填充色为纯黑色,如果承载Bitmap的ImageView背景也是深色/黑色,黑色图案叠在透明背景上就会和ImageView背景融为一体,看起来如同空白。
  • 版本兼容性问题:低版本的androidx.core:core-ktx库(低于1.2.0版本)的toBitmap方法对VectorDrawable的适配存在缺陷,无法正确绘制矢量内容,也会出现空白的问题。

修复方案

  1. 先修正参数,传入正确的宽高:
drawable?.let { d ->
    imageViewArt.setImageBitmap(d.toBitmap(artWidth, artHeight))
}
  1. 如果需要带背景色,可以自己封装扩展方法,手动指定背景色:
fun Drawable.toBitmapWithBackground(width: Int, height: Int, bgColor: Int): Bitmap {
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    canvas.drawColor(bgColor)
    setBounds(0, 0, width, height)
    draw(canvas)
    return bitmap
}

调用时传入你需要的背景色即可。
3. 升级Core KTX版本到1.2.0及以上,解决矢量图适配问题。


内容的提问来源于stack exchange,提问作者John Glen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:45:01