我有這個可組合的,它應該允許使用指向畫布的指針進行繪製,但是當我移動指針時什麼也沒有發生
@ExperimentalComposeUiApi
@Composable
fun CanvasDraw() {
val path = remember { Path() }
Canvas(modifier = Modifier
.fillMaxSize()
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
path.moveTo(it.x, it.y)
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(it.x, it.y)
}
else -> false
}
true
}) {
drawPath(
path = path,
color = Color.Blue,
style = Stroke(10f)
)
}
}
remember { Path() }
正在為下一次重組緩存 lambda 內容值,但當此對像上的內容髮生更改時,它無法觸發重組。要創建一些狀態,這將觸發 Compose 中更改的重新組合,您需要使用某種可變狀態 - 這是為 Compose 製作的新事物。
您可以在文檔中的 Compose 中找到有關狀態的更多信息,包括解釋基本原理的這個 youtube 視頻。
裡面的存儲點Path
不會乾淨,因為它不是基本類型。相反,我使用的是可變狀態點列表,如下所示:
val points = remember { mutableStateListOf<Offset>() }
Canvas(modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectDragGestures { change, _ ->
points.add(change.position)
}
}
) {
drawPath(
path = Path().apply {
points.forEachIndexed { i, point ->
if (i == 0) {
moveTo(point.x, point.y)
} else {
lineTo(point.x, point.y)
}
}
},
color = Color.Blue,
style = Stroke(10f)
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句