如何在 Android Compose 应用程序中使用 ContentScale.Fit 对加载了 Coil 的 SubcomposeAsyncImage 的图像应用圆角?

问题描述 投票:0回答:1

我正在开发一个 Android Compose 应用程序,并使用 Coil 的 SubcomposeAsyncImage 异步加载图像。我想对这些图像应用圆角,同时使用 ContentScale.Fit 确保它们保持纵横比。图像也应该最大。

以下是相关代码片段:

Column(
    modifier =
        modifier
            .fillMaxSize()
            .background(Color.Cyan),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center,
) {
    SubcomposeAsyncImage(
        modifier =
            Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(8.dp))
                .background(Color.Blue),
        model = model.build(),
        contentScale = ContentScale.Fit,
        contentDescription = null,
        loading = {},
        error = {},
    )
}

例如,当我使用此测试图像时:

enter image description here

我得到这个结果:

enter image description here

因此 RoundedCornerShape 不会应用于图像,而仅应用于保存图像的容器。我该如何解决这个问题?

android image android-jetpack-compose scale coil
1个回答
0
投票

问题的主要原因是

.fillMaxSize()
修改器将使用所有可用空间。相反,您希望图像在缩放图像以填充最大可用宽度后仅使用必要的高度。

不幸的是,没有可用的修饰符组合来确定该高度。相反,你必须通过指定其中之一来给它一个线索

  • 要保持的纵横比
  • 具体使用尺寸

这是一个使用

Image
的示例,因为该问题并非 Coil 所独有
SubcomposeAsyncImage

Column(modifier = Modifier.fillMaxSize()) {

        // using aspect ratio
        Image(
            painter = painterResource(id = R.drawable.test_image),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .aspectRatio(1f)
                .fillMaxSize()
                .clip(RoundedCornerShape(40.dp))
        )

        // using size
        Image(
            painter = painterResource(id = R.drawable.test_image),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(400.dp)
                .fillMaxSize()
                .clip(RoundedCornerShape(40.dp))
        )
    }

可以使用线圈拦截器或进行一些测量来动态计算任何图像的纵横比。与此同时,在不知道长宽比或没有您想要的特定尺寸或长宽比的情况下,我不知道有任何其他方法可以做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.