Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joshuajhomann/aa93ef1729bd3b49fc2e92d33a14ae34 to your computer and use it in GitHub Desktop.
Save joshuajhomann/aa93ef1729bd3b49fc2e92d33a14ae34 to your computer and use it in GitHub Desktop.
UIImagePixel
func pixel(in image: UIImage, at point: CGPoint) -> (UInt8, UInt8, UInt8, UInt8)? {
let width = Int(image.size.width)
let height = Int(image.size.height)
let x = Int(point.x)
let y = Int(point.y)
guard x < width && y < height else {
return nil
}
guard let cfData:CFData = image.cgImage?.dataProvider?.data, let pointer = CFDataGetBytePtr(cfData) else {
return nil
}
let bytesPerPixel = 4
let offset = (x + y * width) * bytesPerPixel
return (pointer[offset], pointer[offset + 1], pointer[offset + 2], pointer[offset + 3])
}
let image = UIImage(named: "t.png")!
if let (r,g,b,a) = pixel(in: image, at: CGPoint(x: 1, y:2)) {
print ("Red: \(r), Green: \(g), Blue: \(b), Alpha: \(a)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment