图形上下文是预期的两倍

问题描述

我正在开发用于绘图的Swift MacOS应用程序。以下代码子集显示了我的问题。

import Cocoa

class AppDelegate: NSObject,NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        var window: NSWindow!
        window = NSWindow(contentRect: NSMakeRect( 0,1000,1000 ),styleMask:[.titled,.closable,.miniaturizable,.resizable],backing: .buffered,defer: false)
        window.makeKeyAndOrderFront(window)

        print("windowHeight = \(window.frame.height)")
        print("windowWidth  = \(window.frame.width)")
    
        let view = Renderer( frame:NSMakeRect( 0,1000 ) )
        view.autoresizingMask = [.width,.height]
        window.contentView!.addSubview (view)

        print("viewHeight = \(view.frame.height)")
        print("viewWidth  = \(view.frame.width)")
    }
        
    func applicationShouldTerminateAfterLastwindowClosed(_ sender: NSApplication) -> Bool{return true}
    func applicationWillTerminate(_ aNotification: Notification) { }
}

let appDelegate = AppDelegate()
let application = NSApplication.shared
application.setActivationPolicy(.regular)
application.delegate = appDelegate
application.activate(ignoringOtherApps:true)
application.run()


class Renderer: NSView {
            
    override func draw(_ rect: NSRect) {
        super.draw(rect)
        
        print("rectHeight = \(rect.height)")
        print("rectWidth  = \(rect.width)")
        
        guard let gc = NSGraphicsContext.current?.cgContext else {return}  // gc = graphics context
        
        print("gc.height = \(gc.height)")
        print("gc.width  = \(gc.width)")
        
        // The rest of my drawing code goes here.
    }
}

运行此代码时,打印输出为:

    windowHeight = 1022.0   windowWidth = 1000.0
    viewHeight   = 1000.0   viewWidth   = 1000.0
    rectHeight   = 1000.0   rectWidth   = 1000.0
    gc.height    = 2000     gc.width    = 2000

当我声明窗口,视图和矩形的大小均为1000 x 1000时,为什么当前的GraphicsContext会说它的大小为2000 x 2000?

解决方法

因为您的计算机具有双分辨率(Retina)屏幕。