I recently started adding graphic charts to a MacOS application I wrote. The first chart is great and I added a second chart where I ran into a fundamental way the code operates that I did not/do not understand. The only reason I ran into this is because in my second chart I used random to draw some bubbles inside confined areas. It works nicely but when I resized the view window a little bit the chart redrew everything and since I was using random the first set of bubbles remained in the screen and the second set were added to the screen. So I made a simple example to illustrate.
class GraphView: NSView {
var dcnt = 0
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
dcnt+=1
print(dcnt)
let path = NSBezierPath(rect: self.bounds)
var rec = NSRect()
var circ = NSBezierPath()
NSColor.lightGray.setFill()
path.fill()
rec = NSRect(x:Int.random(in: 100...900), y:Int.random(in: 70...560), width:50, height:50)
NSColor.red.setFill()
circ = NSBezierPath(ovalIn: rec)
circ.fill()
circ.stroke()
}
}
This is run from a simple ViewController that calls the GraphView. I added a counter to print out and see what is happening. Also, if I drag the chart/view window over to a second monitor, it also forces a redraw.
How do I stop this from happening. I want to draw the chart and that is it. No clicking, dragging, resizing (I have disabled resizing the window) should redraw anything.
Here is an example of what happens when I drag the chart to a secondary monitor...

A window resize causes view resizes. The secondary display may have a different resolution.
You can't,
drawis called multiple times.Create a
NSImageof the chart and display it in aNSimageView.Calculate the coordinates or rect of the circle once when the view is created so
drawwill always draw the same circle.