使用SwiftUI $ Xcode for macOS,当鼠标在CGImage上时,如何获得鼠标在图像坐标中的位置?

yr9zkbsy  于 2023-05-30  发布在  Swift
关注(0)|答案(1)|浏览(98)

我在我的ContentView上显示灰度图像,这些图像已经缩放到UInt8,并且希望在鼠标悬停在图像上时获得鼠标相对于图像原点的位置。(我计划使用获取并显示原始UInt16数据中的值)。
我正在检测其他鼠标位置以更改光标等。但是通过搜索无法找到任何解决方案。
下面是经过轻微编辑的代码:

struct CGImageView: View {
    @Binding var filename: String?
    @Binding var minMax: [UInt16]

    @State private var opacity = 0.0
    
    var body: some View {
            // probably should move this elswhere
        let data = importAndScaleImageData(filename!)
        let grayCGImageRef = createCGImageFromUint8(data, height: 240, width: 320)
        
        HStack {
            GeometryReader { geometry in
                Image(decorative: grayCGImageRef, scale: 1.0)
                    .aspectRatio(contentMode: .fit)
                    .border(Color.white)
            }
            .frame(width: CGFloat(grayCGImageRef.width), height: CGFloat(grayCGImageRef.height))
            .onHover { (hover: Bool) in
                if hover {
                    NSCursor.crosshair.push()
                } else {
                    NSCursor.pop()
                }
            }
            .onContinuousHover { 
                // *** get mouse location

            }
            .padding(10)
        }
    }
}
fnx2tebb

fnx2tebb1#

要获取鼠标位置,可以尝试这种方法,如以下示例代码所示:

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "house")
                .resizable()
                .frame(width: 222, height: 222)
                .border(.red)
                .onHover { hover in
                    if hover {
                        NSCursor.crosshair.push()
                    } else {
                        NSCursor.pop()
                    }
                }
                .onContinuousHover { phase in
                    switch phase {
                    case .active(let location):
                        print("---> location: \(location)")
                    case .ended:
                        break
                    }
                }
        }.frame(width: 444, height: 444)
    }
}

注意,图像的左上角是location(0,0),您可能需要进行一些坐标转换才能获得所需的内容。

相关问题