
This video is only available to subscribers. Start a subscription today to get access to this and 419 other videos.
Working in AppKit
This episode is part of a series: Dive Into Core Graphics.
1. Intro 2 min |
2. Basic Shapes 7 min |
3. Paths 17 min |
4. Colors 9 min |
5. Gradients 11 min |
6. Clipping Paths 6 min |
7. Context Transforms 10 min |
8. Images 7 min |
9. Text 9 min |
10. Offscreen Rendering 12 min |
11. Custom CALayer 13 min |
12. Pie Progress View 7 min |
13. Watermarking Photos 6 min |
14. Working in AppKit 8 min |
Preparing the Cocoa Playground
import AppKit // or Cocoa
import PlaygroundSupport
final class CustomView: NSView {
}
let view = CustomView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
PlaygroundPage.current.liveView = view
Getting Layer-backed NSViews
By default NSView
is not backed by a layer. To change this:
view.wantsLayer = true
view.layer
Flipping the Drawing
NSView
by default draws upside down compared to UIView
. To change this you can invert the y-axis like we’ve seen before, or we can override isFlipped
:
override var isFlipped: Bool {
return true
}
Drawing in an NSView
override func draw(_ dirtyRect: NSRect) {
NSColor.white.setFill()
context.fill(bounds)
NSColor.blue.setFill()
context.fill(CGRect(x: 20, y: 20, width: 150, height: 150))
let text = "Hello" as NSString
text.draw(at: CGPoint(x: 20, y: 190), withAttributes: [:])
}
Differences here are using NSColor
over UIColor
.
Drawing into an NSImage
Drawing into an NSImage
is a bit different than UIImage
as well. We’ll create a new instance of NSImage
and pass a block to it that we can use to do our drawing. To get the context, we call NSGraphicsContext.current()
and it returns an object that we can use to get the cgContext
from.
let image = NSImage(size: CGSize(width: 320, height: 320), flipped: true) { bounds in
guard let context = NSGraphicsContext.current()?.cgContext else { return false }
NSColor.white.setFill()
context.fill(bounds)
NSColor.blue.setFill()
context.fill(CGRect(x: 20, y: 20, width: 150, height: 150))
let text = "Hello" as NSString
text.draw(at: CGPoint(x: 20, y: 190), withAttributes: [:])
return true
}
image