Skip to content

Instantly share code, notes, and snippets.

@KrisYu
Forked from marchinram/UIImage+PixelColor.swift
Created September 29, 2017 01:49
Show Gist options
  • Save KrisYu/cade8eb6276f36896043c86cdbe65ca8 to your computer and use it in GitHub Desktop.
Save KrisYu/cade8eb6276f36896043c86cdbe65ca8 to your computer and use it in GitHub Desktop.
iOS Swift UIImage subscript extension to get pixel color
import UIKit
extension UIImage {
subscript (x: Int, y: Int) -> UIColor? {
if x < 0 || x > Int(size.width) || y < 0 || y > Int(size.height) {
return nil
}
let provider = CGImageGetDataProvider(self.CGImage)
let providerData = CGDataProviderCopyData(provider)
let data = CFDataGetBytePtr(providerData)
let numberOfComponents = 4
let pixelData = ((Int(size.width) * y) + x) * numberOfComponents
let r = CGFloat(data[pixelData]) / 255.0
let g = CGFloat(data[pixelData + 1]) / 255.0
let b = CGFloat(data[pixelData + 2]) / 255.0
let a = CGFloat(data[pixelData + 3]) / 255.0
return UIColor(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