如何在自定义 CALayer 子类的重写绘图函数中在 macOS 上绘制字符串?
How do you draw a string on macOS in overriden draw-function of a custom CALayer subclass?
为什么以下代码在 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 绘图方法使用这个全局上下文。由于您在核心动画级别编写代码,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])
}
}
为什么以下代码在 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 绘图方法使用这个全局上下文。由于您在核心动画级别编写代码,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])
}
}