Created
April 10, 2019 16:18
-
-
Save joshuajhomann/aa93ef1729bd3b49fc2e92d33a14ae34 to your computer and use it in GitHub Desktop.
UIImagePixel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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