Jetpack Compose:如何剪出卡片形状?

Coo*_*ter 2 android-jetpack-compose

我想在相机预览上方创建一个半透明图层,如下所示:

在此输入图像描述

我在我的应用程序中完成了相机预览,我想要的只是在预览上有一个半透明的图层,带有剪裁的卡片形状,如图所示(带有圆角)。

所以:全屏相机预览,上面有一个全屏半透明覆盖层,其中有一个卡片状的孔被切掉

我怎样才能做到这一点?

Thr*_*ian 5

您可以使用 BlendModes 将矩形从透明层中排除

@Composable
private fun TransparentCamLayout() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .drawWithContent {

                val canvasWidth = size.width
                val canvasHeight = size.height
                val width = canvasWidth * .9f
                val height = width * 3 / 4f

                drawContent()

                drawWithLayer {

                    // Destination
                    // This is transparent color
                    drawRect(Color(0x99000000))

                    // Source
                    // This is where we extract this rect from transparent
                    drawRect(
                        topLeft = Offset((canvasWidth - width) / 2, canvasHeight * .3f),
                        size = Size(width, height),
                        color = Color.Transparent,
                        blendMode = BlendMode.SrcIn
                    )
                }

                drawRect(
                    topLeft = Offset((canvasWidth - width) / 2, canvasHeight * .3f),
                    size = Size(width, height),
                    color = Color.White,
                    style = Stroke(2.dp.toPx())
                )
            }
    ) {
        Image(
            modifier = Modifier.fillMaxSize(),
            painter = painterResource(id = R.drawable.landscape5),
            contentScale = ContentScale.Crop,
            contentDescription = null
        )
    }
}

/**
 * Draw with layer to use [BlendMode]s
 */
private fun DrawScope.drawWithLayer(block: DrawScope.() -> Unit) {
    with(drawContext.canvas.nativeCanvas) {
        val checkPoint = saveLayer(null, null)
        block()
        restoreToCount(checkPoint)
    }
}
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述

在本教程的BlendMode 部分中,您可以找到其他用法。正如在自定义剪辑的答案中一样,构建评级栏,并且有许多用途限制了您的想象力。Blend 或 PorterDuff 模式对于构建自定义剪辑、Alpha 混合或像素操作非常有用。