You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose中使用android.graphics.Path适配挖孔屏?

解决Android原生Path转Jetpack Compose Path的问题
  • 核心思路:原生android.graphics.Path和Compose的androidx.compose.ui.graphics.Path没有直接转换API,需要通过遍历原生Path的路径指令,逐个映射到Compose Path的方法。

实现转换扩展函数

可以写一个扩展函数,利用PathIterator遍历原生Path的每一段路径操作,然后构建Compose的Path:

import android.graphics.Path as AndroidPath
import android.graphics.PathIterator
import androidx.compose.ui.graphics.Path as ComposePath

fun AndroidPath.toComposePath(): ComposePath {
    val composePath = ComposePath()
    val points = FloatArray(8) // 存储路径指令的坐标点,最多需要8个(比如 cubicTo)
    
    val iterator = this.pathIterator(null, 1f)
    while (!iterator.isDone) {
        when (iterator.next(points)) {
            PathIterator.SEG_MOVETO -> composePath.moveTo(points[0], points[1])
            PathIterator.SEG_LINETO -> composePath.lineTo(points[0], points[1])
            PathIterator.SEG_QUADTO -> composePath.quadraticBezierTo(points[0], points[1], points[2], points[3])
            PathIterator.SEG_CUBICTO -> composePath.cubicTo(points[0], points[1], points[2], points[3], points[4], points[5])
            PathIterator.SEG_CLOSE -> composePath.close()
        }
    }
    return composePath
}

实际使用示例

获取挖孔区域路径并转换后,就可以在Compose Canvas中使用,比如用来让图像适配挖孔区域显示:

@Composable
fun CutoutBehindImage() {
    val view = LocalView.current
    val imageBitmap = ImageBitmap.imageResource(LocalContext.current.resources, R.drawable.your_image)
    
    val cutoutPath = remember {
        val displayCutout = view.rootWindowInsets.displayCutout
        displayCutout?.cutoutPath?.toComposePath() ?: ComposePath()
    }

    Canvas(modifier = Modifier.fillMaxSize()) {
        // 绘制全屏图像
        drawImage(imageBitmap)
        
        // 用挖孔路径裁剪绘制遮挡层,让挖孔区域露出下方图像
        clipPath(cutoutPath) {
            drawRect(color = Color.White) // 颜色需和页面背景保持一致
        }
    }
}

注意:获取displayCutout时要确保View已完成布局,可配合LaunchedEffect或rememberUpdatedState避免空值问题。

内容的提问来源于stack exchange,提问作者Александр Милакин

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:18:19