Created
September 10, 2018 12:41
-
-
Save shaps80/3a8ff6846ef1e2739e82acfcf81c0520 to your computer and use it in GitHub Desktop.
Swift Image from Color. Supports both UIImage and NSImage for cross-platform compatibility.
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
#if os(iOS) | |
import UIKit | |
public typealias PlatformImage = UIImage | |
public typealias PlatformColor = UIColor | |
#else | |
import AppKit | |
public typealias PlatformImage = NSImage | |
public typealias PlatformColor = NSColor | |
#endif | |
extension PlatformImage { | |
public convenience init(color: PlatformColor) { | |
let size = CGSize(width: 1, height: 1) | |
#if os(iOS) | |
let image = UIGraphicsImageRenderer(size: size).image { context in | |
color.setFill() | |
context.fill(context.format.bounds) | |
}.resizableImage(withCapInsets: .zero) | |
self.init(cgImage: image.cgImage!) | |
#else | |
self.init(size: size, flipped: false) { rect in | |
color.setFill() | |
rect.fill() | |
return true | |
} | |
resizingMode = .stretch | |
capInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage. Can be pasted directly into a playground with the above code.