首页 > 解决方案 > Jetpack Compose:使父级之外的偏移图像可见

问题描述

我在带有背景颜色的卡片内添加了一个图像,我希望我的图像的某些部分溢出容器之外并且可见。我曾经offset偏移图像,但我找不到让它可见的方法。

这是我的代码:

Card(
    shape = RoundedCornerShape(8.dp),
    modifier = Modifier.padding(),
    backgroundColor = Color.Cyan,
    onClick = {},
) {
    Box(modifier = Modifier.wrapContentHeight()) {

        Image(
            modifier = Modifier
                .width(250.dp)
                .align(alignment = Alignment.TopEnd)
                .offset(y = -75.dp, x = 50.dp),
            painter = painterResource(id = R.drawable.ic_pray),
            contentDescription = null,
        )
        Column(

        ) {}
    }
}

屏幕截图

标签: kotlinandroid-layoutandroid-jetpack-compose

解决方案


Card基于材质表面,它使用 Modifier.clip它来防止显示您的偏移视图。

如果需要保持Card高度,可以将图像放置在Box外部Card

Box {
    Card(...)
    Image(
        modifier = Modifier
            .width(250.dp)
            .align(alignment = Alignment.TopEnd)
            .offset(y = -75.dp, x = 50.dp),
        painter = painterResource(id = R.drawable.my_image),
        contentDescription = null,
    )
}

否则,您可以Card首先跳过使用,并将背景和形状设置为您的Boxwith Modifier.background

Box(
    modifier = Modifier
        .padding(10.dp)
        .background(Color.Cyan, shape = RoundedCornerShape(8.dp))
) {
    Box(modifier = Modifier.wrapContentHeight()) {
        Image(
            modifier = Modifier
                .width(250.dp)
                .align(alignment = Alignment.TopEnd)
                .offset(y = -75.dp, x = 50.dp),
            painter = painterResource(id = R.drawable.my_image),
            contentDescription = null,
        )
        Column(

        ) {}
    }
}

推荐阅读