Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Last active April 6, 2018 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usagimaru/46118ef276a691f74ddbb097b0f25cd5 to your computer and use it in GitHub Desktop.
Save usagimaru/46118ef276a691f74ddbb097b0f25cd5 to your computer and use it in GitHub Desktop.
Optimize NSView's drawRect
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard let ctx = NSGraphicsContext.current?.cgContext else {return}
var rects: UnsafePointer<NSRect>?
var count = 0
self.getRectsBeingDrawn(&rects, count: &count)
if let rects = rects {
for i in 0..<count {
let rect = rects[i]
let objectFrame: NSRect = <#object's frame#>
if NSIntersectsRect(objectFrame, rect) {
// drawing code for object
}
}
}
}
}
// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaViewsGuide/Optimizing/Optimizing.html
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard let ctx = NSGraphicsContext.current?.cgContext else {return}
let objectFrame: NSRect = <#object's frame#>
if self.needsToDraw(objectFrame) {
// drawing code for object
}
}
}
// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaViewsGuide/Optimizing/Optimizing.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment