swift - 将 NSString 绘制到 CALayer 中

标签 swift macos cocoa core-graphics

出于动画原因,我必须将 NSString 绘制到 CALayer 对象中。这就是我无法使用 CATextLayer 的原因。

问题是我无法在屏幕上显示文本。 我知道我必须在graphicsContext 内部进行绘制,这是在drawInContext() 内移交的。我不知道如何从 CGContext 实例创建 NSGraphicsContext 实例。 GraphicsContextWithGraphicsPort 类方法已弃用。有什么替代品吗?

注意:我使用的是 Swift。

最佳答案

您现在可以使用init(CGContext graphicsPort: CGContext, flipped initialFlippedState: Bool)初始化程序。

因此,例如,如果您要子类化 CALayer 并重写 drawInContext() 函数,您的代码将如下所示:

override func drawInContext(ctx: CGContext) {

    NSGraphicsContext.saveGraphicsState() // save current context

    let nsctx = NSGraphicsContext(CGContext: ctx, flipped: false) // create NSGraphicsContext
    NSGraphicsContext.setCurrentContext(nsctx) // set current context

    NSColor.whiteColor().setFill() // white background color
    CGContextFillRect(ctx, bounds) // fill

    let text:NSString = "Foo bar" // your text to draw

    let paragraphStyle = NSMutableParagraphStyle() // your paragraph styling
    paragraphStyle.alignment = .Center

    let textAttributes = [NSParagraphStyleAttributeName:paragraphStyle.copy(), NSFontAttributeName:NSFont.systemFontOfSize(50), NSForegroundColorAttributeName:NSColor.redColor()] // your text attributes

    let textHeight = text.sizeWithAttributes(textAttributes).height // height of the text to render, with the attributes
    let renderRect = CGRect(x:0, y:(frame.size.height-textHeight)*0.5, width:frame.size.width, height:textHeight) // rect to draw the text in (centers it vertically)

    text.drawInRect(renderRect, withAttributes: textAttributes) // draw text

    NSGraphicsContext.restoreGraphicsState() // restore current context
}

委托(delegate)实现是相同的。

关于swift - 将 NSString 绘制到 CALayer 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35639820/

相关文章:

ios - 从我的应用程序打开优步,在不使用 sdk 的情况下预先填充上车和下车位置

ios - 在准备 segue 之前从闭包中提取数组 - Swift

swift - iOS Swift - 如何将控制台输出保存为文本文件(即 println()、NSLog())

c++ - 如何永久覆盖 HOMEBREW_CC 和 HOMEBREW_CXX 设置?

objective-c - 在 Objective-C/Carbon 中与 AFP 合作

macos - 有没有办法获取 CFStreamError 的字符串描述?

iOS 键盘扩展 : able to display key tap beyond keyboard field?

c++ - 依赖于操作系统的 C++ 内存泄漏?

cocoa - 检查 Cocoa Document Based 应用程序中保存是否成功

swift - 尝试在 OSX 上使用 CoreSpotlight