swift - 如何在自定义 CALayer 子类的重写绘图函数中在 macOS 上绘制字符串?

标签 swift string macos calayer cgcontext

为什么以下代码不能在 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])
    }
}

最佳答案

CALayerdraw(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/

相关文章:

Android 日期到字符串转换问题

macos - 如何在 Mac OS X 上安装 libuuid?

macos - Theano 或 Tensor 流作为 Mac 上的 Keras 后端

ios - 在 Cloud Code 中解析 LiveQuery

iOS swift : Propagates Swipe Events from nester controller to underneath controller

python 字符串替换错误地删除了空格

java - 一台mac上是否可以安装两个java SDK?

ios - 不要在 UITextField 返回时关闭键盘

swift - 排序结构 -> 二元运算符 '<' 不能应用于两个 'String?' 操作数

java - 在保留完整单词的同时在 Java 中修剪字符串