您如何在macOS上以自定义CALayer子类的替代绘制功能绘制字符串?

问题描述 投票:0回答:1

为什么以下代码未在macOS应用程序中绘制字符串?

class MyLayer: CALayer {
    override func draw(in ctx: CGContext) {
        let font = NSFont.systemFont(ofSize: 18)
        let text = "TEXT"
        let textRect = CGRect(x: 100, y: 100, width: 100, height: 100)
        text.draw(in: textRect, withAttributes: [.font: font])
    }
}
swift string macos calayer cgcontext
1个回答
0
投票

CALayerdraw(in:)方法是建立在Core Graphics之上的。所有Core Graphics绘图函数都将CGContext作为参数(或者在Swift中是CGContext上的方法)。这就是Core Animation将CGContext传递给draw(in:)方法的原因。

但是,draw(in:withAttributes:)上的String方法不是Core Graphics的一部分。它是AppKit的一部分。 AppKit的绘制方法不能直接在CGContext上操作。它们在NSGraphicsContext(包装CGContext)上运行。但是,从draw(in:withAttributes:)方法中可以看到,AppKit的绘图函数不带NSGraphicsContext参数,也不是NSGraphicsContext上的方法。

相反,有一个全局(每个线程)NSGraphicsContext。 AppKit绘制方法使用此全局上下文。由于您是在Core Animation级别上编写代码的,因此AppKit并未为您设置全局NSGraphicsContext。您需要自己设置:

class MyLayer: CALayer {
    override func draw(in ctx: CGContext) {
        let nsgc = NSGraphicsContext(cgContext: ctx, flipped: false)
        NSGraphicsContext.current = nsgc

        let font = NSFont.systemFont(ofSize: 18)
        let text = "TEXT"
        let textRect = CGRect(x: 100, y: 100, width: 100, height: 100)
        text.draw(in: textRect, withAttributes: [.font: font])
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.