我有一个图像视图,当光标位于图像上时,它显示图像和 CGPoint。我能够获取并显示光标位置(以像素为单位),但无法弄清楚如何获取像素 rgb 的值。
import SwiftUI
struct ImageView: View {
@State var location: CGPoint = .zero
@State var didHover = false
var body: some View {
VStack {
Text("Os três")
.font(.system(size: 16))
Image("Burros_1") // placeholder
.resizable()
.scaledToFit()
.aspectRatio(contentMode: .fit)
.background(Color.black.opacity(0.5))
.frame(width: 640, height: 480)
.border(.green)
.onHover { hover in
if hover {
NSCursor.crosshair.push()
} else {
NSCursor.pop()
}
}
.onContinuousHover { phase in // (col, row)
switch phase {
case .active(let location):
NSCursor.crosshair.push()
self.location = location // WORKS
self.didHover = true
case .ended:
self.didHover = false
break
}
}
// GOAT add DN
let rowString = String(format: "%03d", Int(round(location.x)))
let colString = String(format: "%03d", Int(round(location.y)))
if didHover { // Missing pixel value GOAT
Text("(r, c, DN) \(rowString), \(colString), ??")
.monospaced()
}
else { // this conserves a line for the Text
Text(" ")
}
} // VStack
} //
}
我在网上进行了广泛的搜索,包括堆栈溢出,但大多数结果都是针对 iOS 的,而不是 macOS,并且并没有真正解决我的问题或无法编译。我也“跳”到定义来尝试找到一种方法,但没有成功。
您可以使用
NSBitmapImageRep
尝试这种方法,以获得像素 RGB。
示例代码:
struct ContentView: View {
var body: some View {
ImageView()
}
}
struct ImageView: View {
let nsimg = NSImage(named: "mycat")!
@State private var location: CGPoint = .zero
@State private var pixelColor: NSColor?
var body: some View {
VStack {
Text("location: \(location.debugDescription)")
Text("color: \(pixelColor?.debugDescription ?? "no color")")
GeometryReader { geo in
Image(nsImage: nsimg)
.resizable()
.frame(width: 640, height: 480)
.onContinuousHover { phase in
switch phase {
case .active(let location):
NSCursor.crosshair.push()
self.location = location
// todo convert coords using GeometryReader
pixelColor = nsimg.colorAt(location)
case .ended:
break
}
}
.border(.green)
}
}
.onAppear {
pixelColor = nsimg.colorAt(CGPoint(x: 20, y: 60)) // for testing
print("---> pixelColor: \(pixelColor)")
}
}
}
extension NSImage {
func colorAt(_ pos: CGPoint) -> NSColor? {
let imageRep = NSBitmapImageRep(data: self.tiffRepresentation!)
return imageRep?.colorAt(x: Int(pos.x), y: Int(pos.y))
}
}