将NSString绘制到CALayer中

man*_*ahn 2 macos cocoa core-graphics swift

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

问题是我无法在屏幕上看到文字.我知道我必须在graphicsContext中绘制,这是在drawInContext()中传递的.我无法弄清楚如何从CGContext实例中创建NSGraphicsContext实例.不推荐使用graphicsContextWithGraphicsPort类方法.它有替代品吗?

注意:我使用的是Swift.

Ham*_*ish 5

您现在可以使用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
}
Run Code Online (Sandbox Code Playgroud)

代表实现将是相同的.