解决Compose在安卓手机上加载gif图片异常问题

249 阅读1分钟

将原有的 painterResource 换成以下方法 painterResourceCompat 即可

@Composable
fun painterResourceCompat(@DrawableRes id: Int): Painter {
    val context = LocalContext.current
    val res = context.resources
    val value = remember { TypedValue() }
    res.getValue(id, value, true)
    val path = value.string
    if (path?.endsWith(".xml") == true) {
        return painterResource(id = id)
    }
    val imageBitmap = remember(path, id, context.theme) {
        try {
            ImageBitmap.imageResource(res, id)
        } catch (throwable: Throwable) {
            val drawable: Drawable =
                ContextCompat.getDrawable(context, id) ?: throw IllegalArgumentException("not found drawable, path: $path")
            drawable.toBitmap().asImageBitmap()
        }
    }
    return BitmapPainter(imageBitmap)
}

解决的方案是在 13 行 ImageBitmap.imageResource(res, id) 执行异常的时候加入了以下适配的代码

val drawable: Drawable = ContextCompat.getDrawable(context, id) ?: throw IllegalArgumentException("not found drawable, path: $path") 
drawable.toBitmap().asImageBitmap()