美文网首页
解决Compose在Android 7上面加载图片出现异常:On

解决Compose在Android 7上面加载图片出现异常:On

作者: 伪装的狼 | 来源:发表于2023-06-01 18:12 被阅读0次

在使用Compose的项目上线之后,多了一些加载图片的Crash,Firebase查看异常堆栈信息:

Fatal Exception: java.lang.IllegalArgumentException: Only VectorDrawables and rasterized asset types are supported ex. PNG, JPG
       at androidx.compose.ui.res.PainterResources_androidKt.loadImageBitmapResource(PainterResources.android.kt:111)
       at androidx.compose.ui.res.PainterResources_androidKt.access$loadImageBitmapResource(PainterResources.android.kt:1)
       at androidx.compose.ui.res.PainterResources_androidKt.painterResource(PainterResources.android.kt:70)

然后定位到异常代码:

Image(
    painter = painterResource(id = R.drawable.ic_pic),
    contentDescription = ""
)

咋一看,没什么问题,加载的ic_pic是放在drawable里面的图片,按道理来说用官方的api加载图片不会出现什么问题的。但是就是报错了,报错的Android版本都是7.0,另外值得一提的是,出现问题图片资源都是放在drawable这个目录下面,实际用真机测试也难以复现。

painterResource是一个Compose函数,官方使用说明如下:

从 Android 资源 ID 创建一个 [Painter]。这可以分别为基于 [ImageBitmap] 的资产或基于矢量的资产加载 [BitmapPainter] 或 [VectorPainter] 的实例。具有给定 id 的资源必须指向完全光栅化的图像(例如 PNG 或 JPG 文件)或 VectorDrawable xml 资产。此处不支持基于 API 的 xml Drawable。

通过调用 [drawIntoCanvas] 并使用通过 [nativeCanvas] 提供的 Android 框架画布进行绘图,可以将替代的 Drawable 实现与 compose 一起使用。

这里说支持传入png、jpg以及矢量图格式,然而实际传入的是png格式的图片。

看看painterResource函数的源码:

@Composable
fun painterResource(@DrawableRes id: Int): Painter {
    val context = LocalContext.current
    val res = resources()
    val value = remember { TypedValue() }
    res.getValue(id, value, true)
    val path = value.string
    // Assume .xml suffix implies loading a VectorDrawable resource
    return if (path?.endsWith(".xml") == true) {
        val imageVector = loadVectorResource(context.theme, res, id, value.changingConfigurations)
        rememberVectorPainter(imageVector)
    } else {
        // Otherwise load the bitmap resource
        val imageBitmap = remember(path, id, context.theme) {
            loadImageBitmapResource(res, id)
        }
        BitmapPainter(imageBitmap)
    }
}

可以看到png格式图片会走到loadImageBitmapResource(res, id),继续跟进:

private fun loadImageBitmapResource(res: Resources, id: Int): ImageBitmap {
    try {
        return ImageBitmap.imageResource(res, id)
    } catch (throwable: Throwable) {
        throw IllegalArgumentException(errorMessage)
    }
}

这里看到了throw IllegalArgumentException(errorMessage),抛出异常,继续查看errorMessage,发现errorMessage正是所报的错误信息。

private const val errorMessage =
    "Only VectorDrawables and rasterized asset types are supported ex. PNG, JPG"

那么就明白是怎么一回事了,实际是ImageBitmap.imageResource这里出现的异常信息,继续跟进可以看到:

fun ImageBitmap.Companion.imageResource(res: Resources, @DrawableRes id: Int): ImageBitmap {
    return (res.getDrawable(id, null) as BitmapDrawable).bitmap.asImageBitmap()
}

这里使用了getDrawable获取drawable,传入drawable id和theme为null,继续查看源码,发现会有一个异常抛出,猜测Android的bug导致了NotFoundException。

public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
        throws NotFoundException {
    return getDrawableForDensity(id, 0, theme);
}

这里引起了一个思考,为什么View系加载图片不会出现这个问题呢?通常使用View系列获取drawable的方式是使用ContextCompat.getDrawable,查看源码:

@Nullable
    public static Drawable getDrawable(@NonNull Context context, @DrawableRes int id) {
        if (Build.VERSION.SDK_INT >= 21) {
            return Api21Impl.getDrawable(context, id);
        } else if (Build.VERSION.SDK_INT >= 16) {
            return context.getResources().getDrawable(id);
        } else {
            // Prior to JELLY_BEAN, Resources.getDrawable() would not correctly
            // retrieve the final configuration density when the resource ID
            // is a reference another Drawable resource. As a workaround, try
            // to resolve the drawable reference manually.
            final int resolvedId;
            synchronized (sLock) {
                if (sTempValue == null) {
                    sTempValue = new TypedValue();
                }
                context.getResources().getValue(id, sTempValue, true);
                resolvedId = sTempValue.resourceId;
            }
            return context.getResources().getDrawable(resolvedId);
        }
    }

这个是一个适配加载drawable的类,Android 7.0对应的版本号是24,可以看到获取图片会执行到Api21Impl.getDrawable(context, id);。另外,上面的代码还发现了几句话:

在 JELLY_BEAN 之前,当资源 ID 引用另一个 Drawable 资源时,Resources.getDrawable() 将无法正确检索最终配置密度。作为解决方法,请尝试手动解析可绘制对象引用。

然后,还发现了,上面的painterResource函数调用到(res.getDrawable(id, null) as BitmapDrawable).bitmap.asImageBitmap()Api21Impl.getDrawable(context, id)最终都会执行到同一个函数,如下:

public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
            throws NotFoundException {
        return getDrawableForDensity(id, 0, theme);
    }

其中前者传入theme为null,后者在内部调用处传入了getTheme(),区别就是有没有传theme,那么到这里就明白Compose加载图片这个报错是怎么来的了。

那么可总结原因如下:

1、直接调用Resources.getDrawable()获取drawable在低版本机器会有可能出现解析不到资源引用的问题,因为没有传入theme。

2、Compose提供的painterResource()实际最后是调用了Resources.getDrawable(),所以才会有以上Crash。

解决办法:

1、图片资源移动到drawable-xxxhdpi限定了相关分辨率的文件夹内。

2、适配painterResource

3、或者用Coil的rememberAsyncImagePainter加载图片

贴出适配代码:

@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)
}

相关文章

网友评论

      本文标题:解决Compose在Android 7上面加载图片出现异常:On

      本文链接:https://www.haomeiwen.com/subject/uitpedtx.html