You need to enable JavaScript to run this app. 如何以每秒60次的频率高效重绘NSView?
优惠活动
大模型
产品
解决方案
定价
更多

如何以每秒60次的频率高效重绘NSView?

Timer 的问题在于:

  • 它不与屏幕刷新率同步,触发时刻可能落在任意位置;
  • 时间间隔会漂移,0.016 并不等于真实的显示同步周期;
  • 在滚动、鼠标追踪等 run loop 模式下可能被暂停;
  • 通过 setNeedsDisplay 只是标记视图为脏,真正的绘制时机仍由 AppKit 决定。

正确做法是使用 CVDisplayLink,它会在屏幕即将刷新时回调,回调时机与 VSync 同步。

实现代码

import Quartz

class View: NSView {

    private var displayLink: CVDisplayLink?

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {
        wantsLayer = true

        CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)

        guard let displayLink = displayLink else { return }

        let callback: CVDisplayLinkOutputCallback = {
            _, _, _, _, _, userInfo in

            guard let userInfo = userInfo else {
                return kCVReturnSuccess
            }

            let view = Unmanaged<View>
                .fromOpaque(userInfo)
                .takeUnretainedValue()

            DispatchQueue.main.async {
                view.needsDisplay = true
            }

            return kCVReturnSuccess
        }

        let userInfo = Unmanaged.passUnretained(self).toOpaque()

        CVDisplayLinkSetOutputCallback(
            displayLink,
            callback,
            userInfo
        )

        CVDisplayLinkStart(displayLink)
    }

    deinit {
        if let displayLink = displayLink {
            CVDisplayLinkStop(displayLink)
        }
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        guard let context = NSGraphicsContext.current?.cgContext else {
            return
        }

        // 使用 context 进行 Core Graphics 绘制
    }
}

显示链接的回调发生在内部线程,所以必须切回主线程再更新 NSView。

进一步减少开销:使用 updateLayer

如果绘制内容可以直接渲染到图层,建议覆盖 wantsUpdateLayer,避免每次都走完整的 draw(_:) 流程:

class View: NSView {

    override var wantsUpdateLayer: Bool {
        return true
    }

    override func updateLayer() {
        guard let layer = layer else { return }

        let width = Int(bounds.width * layer.contentsScale)
        height = Int(bounds.height * layer.contentsScale)

        guard width > 0, height > 0 else { return }

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bytesPerRow = width * 4
        let bitsPerComponent = 8

        var data = [UInt8](
            repeating: 0,
            count: height * bytesPerRow
        )

        guard let context = CGContext(
            data: &data,
            width: width,
            height: height,
            bitsPerComponent: bitsPerComponent,
            bytesPerRow: bytesPerRow,
            space: colorSpace,
            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
        ) else {
            return
        }

        // 在 context 中绘制 Core Graphics 内容

        guard let image = context.makeImage() else { return }
        layer.contents = image
    }
}

显示链接回调中仍然调用:

DispatchQueue.main.async {
    self.needsDisplay = true
}

AppKit 会因为 wantsUpdateLayer 为 true 而调用 updateLayer(),而不是 draw(_:)。

其他需要注意的点

  • 如果只需要兼容较新系统,也可以考虑 macOS 14 提供的 CADisplayLink,但 CVDisplayLink 兼容性更广。
  • 不要用固定的 0.016 假设刷新率;ProMotion 屏幕可能是 120Hz,某些外接屏幕可能是 60Hz 以下。CVDisplayLink 会自动跟随当前屏幕。
  • 若绘制逻辑本身耗时过长,即使同步机制正确,也无法稳定达到 60FPS,应用 Instruments 的 Core Animation 和 Time Profiler 分析实际耗时。
  • 若每一帧只是更新静态图像或计算结果,优先使用 updateLayer();只有需要 AppKit 管理的图形上下文时,再使用 draw(_:)。
  • 如果已经使用 Metal 做 GPGPU,后续也可以考虑把计算结果直接写入 MTKView 或 CAMetalLayer,但这不是必须的;Core Graphics 配合 CVDisplayLink 仍可用于高频绘制。

内容的提问来源于 stack exchange,提问作者 arghhh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 07:06:05