[英]How to add click events to Canvas in JetPack Compose
I used Canvas in Compose to define a line chart.我在 Compose 中使用 Canvas 来定义折线图。
I want to provide click events for the points in the line chart, but I did not find relevant information to solve the problem.我想为折线图中的点提供点击事件,但是我没有找到解决问题的相关信息。
Please provide some interesting ideas or related information.请提供一些有趣的想法或相关信息。
My suggestion would be something like this:我的建议是这样的:
// First, you must keep track the position of the points
// and their respective sizes using a list of Rect
val dotRects = ArrayList<Rect>()
// e.g.:
// dotRects.add(Rect(top = 0f, left = 0f, bottom = 40f, right = 40f))
Canvas(
modifier = Modifier
// other modifiers...
.pointerInput(Unit) {
detectTapGestures(
onTap = { tapOffset ->
// When the user taps on the Canvas, you can
// check if the tap offset is in one of the
// tracked Rects.
var index = 0
for (rect in dotRects) {
if (rect.contains(tapOffset)) {
// Handle the click here and do
// some action based on the index
break // don't need to check other points,
// so break
}
index++
}
}
)
}
) {
// Your chart...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.