I have a SwiftUI image displayed like this:
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
}
)
and a getColor function:
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
}
When I launch the app and touch the Image, the position is well displayed on the console but the color returns 0 0 0 0, example:
(262.3333282470703, 691.6666564941406)
UIExtendedSRGBColorSpace 0 0 0 0
After a long search, I didn't find a way to get a pixel color from an Image in SwiftUI, if someone has a solution or can help me, it would be really nice.
Thank you in advance.