为什么在 window 调整大小或移动(拖动)到辅助显示器(监视器)时自定义 NSView 会重绘?

Why does custom NSView redraw when window is resized or moved (drag) to an secondary display (monitor)?

我最近开始将图表添加到我编写的 MacOS 应用程序中。第一张图表很棒,我添加了第二张图表,其中我 运行 变成了我 not/do 不理解的代码运行的基本方式。我 运行 这样做的唯一原因是因为在我的第二张图表中,我使用 运行dom 在受限区域内绘制了一些气泡。它工作得很好,但是当我稍微调整视图 window 的大小时,图表重新绘制了所有内容,因为我使用的是 运行dom,第一组气泡保留在屏幕中,第二组被添加到屏幕上.所以我做了一个简单的例子来说明。


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()
    }
}

这是 运行 来自调用 GraphView 的简单 ViewController。我添加了一个计数器来打印出来看看发生了什么。另外,如果我将 chart/view window 拖到第二台显示器上,它也会强制重绘。

我该如何阻止这种情况发生。我想绘制图表,仅此而已。没有点击、拖动、调整大小(我已经禁用调整 window 的大小)应该重绘任何东西。

下面是我将图表拖到辅助显示器时发生的情况的示例...

Why does custom NSView redraw when window is resized or moved (drag) to an secondary display (monitor)?

A window 调整大小会导致视图调整大小。辅助显示器可能有不同的分辨率。

How do I stop this from happening.

你不能,draw被调用了多次。

I want to draw the chart and that is it.

创建图表的 NSImage 并将其显示在 NSimageView 中。

the first set of bubbles remained in the screen and the second set were added to the screen

在创建视图时计算一次圆的坐标或矩形,这样 draw 将始终绘制相同的圆。