如何在 JetPack Compose 中给 Canvas 添加点击事件

8

我在Compose中使用Canvas定义了一条线图。

enter image description here

我希望能够为线图中的数据点提供点击事件,但我没有找到相关信息来解决这个问题。

请提供一些有趣的想法或相关信息。

1个回答

7

我的建议是这样的:

// 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...
}

1
非常感谢。我会尝试的。祝你生活愉快。 - Future Deep Gone
@FutureDeepGone 是否找到了您要寻找的内容?能否请您分享一下代码片段?谢谢。 - Mark Delphi
https://github.com/wdfHPY/compose-linechart - Future Deep Gone
1
@Mark Delphi github.com/wdfHPY/compose-linechart
这是我很久以前创建的一个库,运行环境在没有屏幕适配的平板电脑上。
- Future Deep Gone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接