Instantly share code, notes, and snippets.

Embed
What would you like to do?
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