为什么以下代码未在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])
}
}
CALayer
的draw(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])
}
}