如何在 Jetpack Compose 中创建这个圆形形状?

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

我有一个番茄钟应用程序,想使用这个圆形。该形状根据时间值而变化。外面的点并不重要,我想要在我的应用程序上有一个内部的圆形形状。我使用了Jetpack Compose和drawArc和Canvas,但无法实现。

我想要这样的东西:

这是我的代码:

Canvas(modifier.offset(y = 10.dp)) {
    drawArc(
        color = inactiveBarColor,
        startAngle = 90f,      
        sweepAngle = 90f,       
        useCenter = false,
        size = Size(size.width.toFloat(), size.height.toFloat()),
        style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round)
   )
   drawArc(
        color = activeBarColor,
        startAngle = 0f,      
        sweepAngle = 90f,
        useCenter = false,
        size = Size(size.width.toFloat(), size.height.toFloat()),
        style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round)
   )
}

角度值是随机的,仅用于演示

android android-jetpack-compose android-canvas
1个回答
0
投票

你可以这样画。通过更改值,您可以构建精确的时钟形状。并且您需要在代码中将扫描角度从时间转换为角度。

@Preview
@Composable
private fun ClockArcSample() {
    Column {

        var sweepAngle by remember {
            mutableStateOf(90f)
        }

        Canvas(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.Red)
                .aspectRatio(1f)
        ) {
            val canvasWidth = size.width
            val canvasHalfRadius = canvasWidth / 2
            val canvasHeight = size.height
            val arcDiameter = canvasWidth * .6f

            drawCircle(
                color = Color.White,
                style = Stroke(canvasWidth * 0.05f),
                radius = canvasWidth * .38f
            )

            drawArc(
                color = Color.White,
                270f,
                sweepAngle,
                true,
                topLeft = Offset((canvasWidth - arcDiameter) / 2, (canvasWidth - arcDiameter) / 2),
                size = Size(arcDiameter, arcDiameter)
            )

            val strokeWidth = 4.dp.toPx()
            for (i in 0..360 step 6) {
                rotate(i.toFloat()) {
            drawLine(
                color = Color.White,
                strokeWidth = strokeWidth,
                start = Offset(
                    x = canvasWidth * 0.94f,
                    y = center.y
                ),
                end = Offset(
                    x = canvasWidth * 0.98f,
                    y = center.y

                )
            )
                }
            }
        }

        Slider(
            value = sweepAngle,
            onValueChange = { sweepAngle = it },
            valueRange = 0f..360f
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.