Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active June 3, 2019 20:17
Show Gist options
  • Save dagronf/ef4349931fd45289d685b34e956e98c4 to your computer and use it in GitHub Desktop.
Save dagronf/ef4349931fd45289d685b34e956e98c4 to your computer and use it in GitHub Desktop.
Generate an NSImage containing a checkerboard pattern for a specific size.
private extension NSImage {
static func checkerboardImage(ofSize: CGSize, color1: NSColor, color2: NSColor, checkSize: CGFloat = 8) -> NSImage? {
let width = NSNumber(value: Float(checkSize))
let center = CIVector(cgPoint: CGPoint(x: 0, y: 0))
let darkColor = CIColor(cgColor: color1.cgColor)
let lightColor = CIColor(cgColor: color2.cgColor)
let sharpness = NSNumber(value: 1.0)
guard let filter = CIFilter(name: "CICheckerboardGenerator") else {
return nil
}
filter.setDefaults()
filter.setValue(width, forKey: "inputWidth")
filter.setValue(center, forKey: "inputCenter")
filter.setValue(darkColor, forKey: "inputColor0")
filter.setValue(lightColor, forKey: "inputColor1")
filter.setValue(sharpness, forKey: "inputSharpness")
let context = CIContext(options: nil)
guard let cgImage = context.createCGImage(filter.outputImage!, from: CGRect(origin: .zero, size: ofSize)) else {
return nil
}
return NSImage(cgImage: cgImage, size: ofSize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment