android 如何在Jetpack合成中使所有来自API的图像都是一个大小?

mgdq6dx1  于 2022-12-21  发布在  Android
关注(0)|答案(1)|浏览(117)

我有下面的组合来表示一个列表模型-

@Composable
fun DashboardCard(
    modifier: Modifier = Modifier,
    model: DashboardCardModel,
    onCardClicked: (model: DashboardCardModel) -> Unit
) {

    Column(
        modifier = modifier
            .size(200.dp, 200.dp)
            .background(Color.Transparent)
            .padding(16.dp)
            .clickable {
                onCardClicked(model)
            },
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceAround
    ) {
        if (model.showDefaultThumbnail) {
            AsyncImage(
                modifier = Modifier
                    .size(90.dp)
                    .clip(RoundedCornerShape(10.dp)),
                model = model.thumbnailUrl, contentDescription = ""
            )
        } else {
            Image(
                modifier = Modifier
                    .size(90.dp)
                    .clip(RoundedCornerShape(10.dp)),
                painter =  painterResource(id = com.tinytap.R.drawable.tinytap),
                contentDescription = ""
            )
        }
        Image(
            modifier = Modifier
                .size(25.dp)
                .padding(top = 10.dp)
                .alpha(if (model.isCurrentPostOfInterest) 1f else 0f),
            painter = painterResource(id = com.tinytap.R.drawable.post_of_interest),
            contentDescription = null
        )
        Text(
            modifier = Modifier.padding(top = 10.dp),
            fontSize = 16.sp,
            color = Color.White,
            text = model.title,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Text(
            text = model.author,
            fontSize = 12.sp,
            color = Color.LightGray,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

问题是我的Image和AsyncImage都使用固定大小,但有时API给我的图像非常宽,导致UI中出现以下不一致-

我怎样才能使我的图像显示完全一样呢?我试过使用各种作物,但结果都搞乱了我的图像

2cmtqfgy

2cmtqfgy1#

考虑到图像可能更短、更高、更宽或更小。要解决这个问题,我建议您使用线圈以下是一个代码示例,可以解决您的问题:

Card(
    modifier = Modifier.size(119.dp, 92.dp),
    shape = RoundedCornerShape(10.dp)
) {
    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data(imageURL)
            .build(),
        placeholder = painterResource(R.drawable.complex_placeholder),
        error = painterResource(R.drawable.complex_placeholder),
        contentDescription = "complex image",
        contentScale = ContentScale.Crop,//The line that will affect your image size and help you solve the problem.

        )
}

上面的代码将始终显示完全覆盖框与图像的任何情况下,也不要忘记确定容器的大小(卡在我的例子'119,92').
要了解更多关于不同属性及其对代码的影响,请选择最适合您的

在此查看更多信息(随附图片参考):Content scaletype fully illustrated

相关问题