出于动画原因,我必须将 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/