I don't catch perfect RGB color on tap in an ImageView in my application with location coordinate. I wrote this:
extension UIImage {
func getPixelColors(atLocation location: CGPoint, withFrameSize size: CGSize) -> UIColor {
let x: CGFloat = (self.size.width) * location.x / size.width
let y: CGFloat = (self.size.height) * location.y / size.height
let pixelPoint: CGPoint = CGPoint(x: x, y: y)
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelIndex: Int = ((Int(self.size.width) * Int(pixelPoint.y)) + Int(pixelPoint.x)) * 4
let r = CGFloat(data[pixelIndex]) / CGFloat(255.0)
let g = CGFloat(data[pixelIndex+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelIndex+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelIndex+3]) / CGFloat(255.0)
//let testColor = UIColor(red: r, green: g, blue: b, alpha: a)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
I call getPixelColors:
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else {
print("Error: touches is empty.")
return
}
let location = touch.location(in: imgTarget)
let pin = UIImageView(frame: CGRect(x: location.x - 14, y: location.y - 14, width: 30, height: 30))
pin.image = UIImage(named: "gMarker")
imgTarget.addSubview(pin)
rgb = (imgTarget.image?.getPixelColors(atLocation: location, withFrameSize: imgTarget.frame.size))! }
The rgb code is correct if I tap in the central part of the image, the further away I get from the center, the more the error increases