Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created September 10, 2018 12:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/3a8ff6846ef1e2739e82acfcf81c0520 to your computer and use it in GitHub Desktop.
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.
#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
}
}
@shaps80
Copy link
Author

shaps80 commented Sep 10, 2018

Example usage. Can be pasted directly into a playground with the above code.

let image = PlatformImage(color: .red) // optionally you can use UIImage directly if you only need iOS support.
let frame = CGRect(x: 0, y: 0, width: 40, height: 40)

#if os(iOS)
typealias ImageView = UIImageView
#else
typealias ImageView = NSImageView
#endif

let imageView = ImageView(frame: frame)

#if os(OSX)
imageView.imageScaling = .scaleProportionallyUpOrDown
#endif

imageView.image = image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment