Jetpack Compose Image无法加载xml格式adaptive-icon自适应图片

初学使用Compose版本 1.3.0,遇到问题作此记录

1.创建工程

Android创建默认工程自带图标ic_launcher和ic_launcher_round。

在文件夹mipmap-anydpi-v26下有两个xml对应的文件,xml中使用的是

adaptive-icon 标签 。经查询是自适应图标。

2.发现问题

原生Android的ImageView加载没有问题,

使用Compose组件Icon 或Image加载图片 ic_launcher和ic_launcher_round时报错

3.查找解决办法

经查询解决方案如下,非常感谢老哥。原理就是将文件转成bitmap进行加载

https://gist.github.com/tkuenneth/ddf598663f041dc79960cda503d14448

ResourcesCompat.getDrawable(
        LocalContext.current.resources,
        R.mipmap.ic_launcher, LocalContext.current.theme
    )?.let { drawable ->
        val 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)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(8.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                // painter = painterResource(R.mipmap.ic_launcher),
                bitmap = bitmap.asImageBitmap(),
                "An image",
                modifier = Modifier.requiredSize(96.dp)
            )
            Text("Hello Image")
        }
    }

猜你喜欢

转载自blog.csdn.net/sinat_35541927/article/details/128125008