为什么以下代码不能在 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:)
方法的原因。
但是,String
上的 draw(in:withAttributes:)
方法不是 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])
}
}
关于swift - 如何在自定义 CALayer 子类的重写绘图函数中在 macOS 上绘制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58894448/