如何在SwiftUI中鼠标悬停图片时显示光标坐标
实现光标附近显示图片悬停坐标
要在光标附近实时显示图片坐标,你可以通过在图片视图上叠加动态定位的文本视图来实现,以下是修改后的完整代码:
struct ImageView: View { // 存储当前悬停位置与坐标文本显示状态 @State private var hoverLocation: CGPoint = .zero @State private var showCoordinates = false var body: some View { Image("testImage") .resizable() .frame(width: 640, height: 480) .onHover { hover in if hover { NSCursor.crosshair.push() } else { NSCursor.pop() } } .onContinuousHover { phase in switch phase { case .active(let location): hoverLocation = location showCoordinates = true case .ended: showCoordinates = false } } // 叠加坐标文本,跟随光标移动 .overlay( Group { if showCoordinates { Text(String(format: "X: %.1f, Y: %.1f", hoverLocation.x, hoverLocation.y)) .font(.caption) .padding(4) .background(Color.black.opacity(0.7)) .foregroundColor(.white) .cornerRadius(4) // 偏移到光标右下方,避免遮挡十字光标 .offset(x: hoverLocation.x + 15, y: hoverLocation.y + 15) } } ) } }
关键修改说明:
- 用
@State变量hoverLocation实时记录光标在图片内的坐标,showCoordinates控制文本的显示/隐藏状态 - 通过
.overlay将坐标文本叠加在图片上方,利用.offset让文本跟随光标位置移动,偏移量可根据需求调整 - 给文本添加半透明黑色背景和圆角,确保在不同色调的图片上都能清晰读取坐标
- 坐标保留一位小数,兼顾精度与显示简洁性
内容的提问来源于stack exchange,提问作者Nate Lockwood
相关产品推荐
相关产品推荐

