簡體   English   中英

如何在 JetPack Compose 中向 Canvas 添加點擊事件

[英]How to add click events to Canvas in JetPack Compose

我在 Compose 中使用 Canvas 來定義折線圖。 在此處輸入圖片說明

我想為折線圖中的點提供點擊事件,但是我沒有找到解決問題的相關信息。

請提供一些有趣的想法或相關信息。

我的建議是這樣的:

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM