Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created October 13, 2023 06:35
Show Gist options
  • Save sonsongithub/afc90bb25978367e7bae5402b0c461e6 to your computer and use it in GitHub Desktop.
Save sonsongithub/afc90bb25978367e7bae5402b0c461e6 to your computer and use it in GitHub Desktop.
Swift Playground for creating an icon.
//: A Cocoa based Playground to present user interface
import AppKit
import PlaygroundSupport
let nibFile = NSNib.Name("MyView")
var topLevelObjects : NSArray?
Bundle.main.loadNibNamed(nibFile, owner:nil, topLevelObjects: &topLevelObjects)
let views = (topLevelObjects as! Array<Any>).filter { $0 is NSView }
func main() -> NSImage? {
let color = NSColor.clear
let size = CGFloat(128)
let view = NSView(frame: NSRect(x: 0, y: 0, width: size, height: size))
view.wantsLayer = true
view.translatesAutoresizingMaskIntoConstraints = false
view.layer?.backgroundColor = color.cgColor
view.layer?.cornerRadius = 2
let destinationSize = Double(size)
let image = NSImage(size: NSSize(width: destinationSize, height: destinationSize))
guard let icon = NSImage(systemSymbolName: "lightbulb.fill", accessibilityDescription: nil) else { return nil }
guard let frameIcon = NSImage(systemSymbolName: "lightbulb", accessibilityDescription: nil) else { return nil }
var width = Double(1)
var height = Double(1)
print(icon.size)
if icon.size.width < icon.size.height {
width = destinationSize * (icon.size.width / icon.size.height)
height = destinationSize
} else {
width = destinationSize
height = destinationSize * (icon.size.height / icon.size.width)
}
let x = (destinationSize - width) / 2
let y = (destinationSize - height) / 2
image.lockFocus()
guard let ctx = NSGraphicsContext.current?.cgContext else { return nil }
view.layer?.render(in: ctx)
let source = NSRect(origin: CGPoint.zero, size: icon.size)
let destination = NSRect(x: x, y: y, width: width, height: height)
ctx.setFillColor(NSColor.blue.cgColor)
let rect = CGRect(x: x+1, y: y, width: width-2, height: height)
rect.fill()
icon.draw(in: destination, from: source, operation: .destinationIn, fraction: 1)
frameIcon.draw(in: destination, from: source, operation: .darken, fraction: 1)
image.unlockFocus()
return image
}
if let image = main() {
let imageview = NSImageView(image: image)
// Present the view in Playground
PlaygroundPage.current.liveView = imageview
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment