Last active
December 4, 2018 09:13
-
-
Save giulio92/69e4f74217422154bb25d2a35d6710f8 to your computer and use it in GitHub Desktop.
Get pixel color from UIImage in Swift
This file contains hidden or 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 getColorForPixel(image:CGImageRef, point:CGPoint) -> UIColor { | |
let imageWidth = CGImageGetWidth(image) | |
let imageHeight = CGImageGetHeight(image) | |
let imageRect = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight) | |
let bitmapBytesForRow = Int(imageWidth * 4) | |
let bitmapByteCount = bitmapBytesForRow * Int(imageHeight) | |
let colorSpace = CGColorSpaceCreateDeviceRGB() | |
let bitmapMemory = malloc(bitmapByteCount) | |
let bitmapInformation = CGImageAlphaInfo.PremultipliedFirst.rawValue | |
let colorContext = CGBitmapContextCreate(bitmapMemory, imageWidth, imageHeight, 8, bitmapBytesForRow, colorSpace, bitmapInformation) | |
CGContextClearRect(colorContext, imageRect) | |
CGContextDrawImage(colorContext, imageRect, image) | |
let data = CGBitmapContextGetData(colorContext) | |
let dataType = UnsafePointer<UInt8>(data) | |
let offset = 4 * (Int(imageWidth) * Int(point.y)) + Int(point.x) | |
let redComponent = CGFloat(dataType[offset + 1])/255.0 | |
let greenComponent = CGFloat(dataType[offset + 2])/255.0 | |
let blueComponent = CGFloat(dataType[offset + 3])/255.0 | |
return UIColor(red: redComponent, green: greenComponent, blue: blueComponent, alpha: 1.0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you forgot to call
free(bitmapMemory)