我有一个像这样显示的 SwiftUI 图像:
Image("Map")
.resizable()
.gesture(
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
self.position = value.location
print(position)
let color = getColor(at: position)
print(color)
}
.onEnded { _ in
self.position = .zero
}
)
和一个 getColor 函数:
func getColor(at point: CGPoint) -> UIColor{
let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
context.translateBy(x: -point.x, y: -point.y)
let color = UIColor(red: CGFloat(pixel[0]) / 255.0,
green: CGFloat(pixel[1]) / 255.0,
blue: CGFloat(pixel[2]) / 255.0,
alpha: CGFloat(pixel[3]) / 255.0)
pixel.deallocate()
return color
}
当我启动应用程序并触摸图像时,位置在控制台上显示得很好,但颜色返回 0 0 0 0,例如:
(262.3333282470703, 691.6666564941406)
UIExtendedSRGBColorSpace 0 0 0 0
经过长时间的搜索,我没有找到在 SwiftUI 中从 Image 中获取像素颜色的方法,如果有人有解决方案或可以帮助我,那就太好了。
提前致谢。