出于动画的原因,我必须将nsstring绘制到calayer对象中。这就是为什么我不能使用catextlayer。
问题是我无法在屏幕上看到文本。
我知道我必须在drawInContext()中绘制图形上下文,它是在drawInContext()中移交的。我不知道如何从cgContext实例创建nsgraphicContext实例。不推荐使用graphicContextWithgraphicsPort类方法。有替代品吗?
注意:我用的是斯威夫特。

最佳答案

现在可以使用初始化器。
因此,例如,如果您要对init(CGContext graphicsPort: CGContext, flipped initialFlippedState: Bool)进行子类化并重写CALayer函数,那么您的代码将如下所示:

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
}

委托实现将是相同的。

10-08 08:12