我试图使用画布和detectDragGestures
方法画直线,但到目前为止,我只实现了没有任何固定的混乱行为.我正在寻找一个解决方案来确保我的线条始终笔直.
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CanvasAction() {
var centerOffset by remember {
mutableStateOf(Offset.Zero)
}
var points by remember {
mutableStateOf<List<Point>>(listOf())
}
Canvas(
modifier = Modifier
.fillMaxSize()
.pointerInput(key1 = Unit) {
detectDragGestures(
onDragStart = { offset ->
points = points + Point(offset = offset, isStartedPosition = true)
},
onDrag = { change, offset ->
change.historical.forEach {
centerOffset = it.position
}
points = points + change.historical.map {
Point(offset = it.position, isStartedPosition = false)
}
},
)
},
) {
drawCircle(
color = Color.Blue,
radius = 7.dp.toPx(),
center = centerOffset,
)
val path = Path()
points.forEach { point ->
if (point.isStartedPosition) {
path.moveTo(point.offset.x, point.offset.y)
} else {
path.lineTo(point.offset.x, point.offset.y)
}
}
drawPath(
path = path,
color = Color.Blue,
style = Stroke(width = 2.dp.toPx()),
)
}
}