解决Compose在Android 7上面加载图片出现异常:Only VectorDrawables and rasterized asset types are supported ex. P...

在使用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)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容

  • 在正文开始之前的最后,放上 GitHub 链接和引入依赖的 gradle 代码: Github: https://...
    松江野人阅读 5,836评论 0 1
  • 在正文开始之前的最后,放上GitHub链接和引入依赖的gradle代码: Github: https://gith...
    苏苏说zz阅读 670评论 0 2
  • 最近项目里面有用到Rxjava框架,感觉很强大的巨作,所以在网上搜了很多相关文章,发现一片文章很不错,今天把这篇文...
    Scus阅读 6,834评论 2 50
  • 转一篇文章 原地址:http://gank.io/post/560e15be2dca930e00da1083 前言...
    jack_hong阅读 897评论 0 2
  • 来自于:CSDNblog.csdn.net/caihongdao123/article/details/51897...
    于加泽阅读 1,244评论 0 5