Skip to content

Instantly share code, notes, and snippets.

@traviskirton
Created November 30, 2016 19:04
Show Gist options
  • Save traviskirton/e3842510c5f5974916a1ff1cffc713c6 to your computer and use it in GitHub Desktop.
Save traviskirton/e3842510c5f5974916a1ff1cffc713c6 to your computer and use it in GitHub Desktop.
Adds extensions to Image and Color that allow user to grab a color at a specified pixel in an image
public extension Image {
public func color(at point: Point) -> Color {
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
guard let offscreenContext = CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else {
print("Could not create offscreenContext")
return clear
}
offscreenContext.translateBy(x: CGFloat(-point.x), y: CGFloat(-point.y))
layer?.render(in: offscreenContext)
guard let pixelImage = offscreenContext.makeImage() else {
print("Could not create pixel image")
return clear
}
return Color(Image(cgimage:pixelImage))
}
}
public extension Color {
/// Initializes and returns a new Color object made up of a repeating pattern based on a specified Image.
/// ````
/// let p = Color("pattern")
/// ````
/// - parameter pattern: a String, the name of an image to use as a pattern.
public convenience init(_ patternImage: Image) {
let uiim = patternImage.uiimage
self.init(UIColor(patternImage: uiim))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment