Last active
June 3, 2019 20:17
-
-
Save dagronf/ef4349931fd45289d685b34e956e98c4 to your computer and use it in GitHub Desktop.
Generate an NSImage containing a checkerboard pattern for a specific size.
This file contains 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
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