Skip to content

Instantly share code, notes, and snippets.

@zenangst
Last active May 24, 2018 05:25
Show Gist options
  • Save zenangst/b16d06766c580e5d0ccd04472a050081 to your computer and use it in GitHub Desktop.
Save zenangst/b16d06766c580e5d0ccd04472a050081 to your computer and use it in GitHub Desktop.
Converting between view coordinate systems - Example 2
import Cocoa
import PlaygroundSupport
let frame = CGRect(origin: .zero,
size: .init(width: 150, height: 150))
let window = NSView(frame: frame)
window.wantsLayer = true
window.layer?.backgroundColor = NSColor.white.cgColor
let view = NSView(frame: CGRect(origin: .init(x: 25, y: 25),
size: CGSize(width: 100, height: 100)))
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.green.withAlphaComponent(0.5).cgColor
window.addSubview(view)
let subview = NSView(frame: CGRect(origin: .init(x: 25, y: 25),
size: .init(width: 50, height: 50)))
subview.wantsLayer = true
subview.layer?.backgroundColor = NSColor.blue.withAlphaComponent(0.5).cgColor
view.addSubview(subview)
let convertToWindow = subview.convert(subview.bounds, to: window)
// {x 25 y 25 w 50 h 50 }
subview.frame
// {x 50 y 50 w 50 h 50 }
convertToWindow
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment