2016-02-25 40 views
1

由於動畫原因,我必須將NSString繪製到CALayer對象中。這就是爲什麼我不能使用CATextLayer。將NSString繪製到CALayer中

問題是我無法在屏幕上顯示文字。 我知道我必須在drawInContext()內部切換的graphicsContext裏面畫圖。我無法弄清楚如何從CGContext實例中創建NSGraphicsContext實例。 graphicsContextWithGraphicsPort類方法已棄用。有沒有更換它?

注意:我正在使用Swift。

回答

4

您現在可以使用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 
} 

的委託實現將是相同的。

+0

你是完全正確的!非常感謝!我應該看看頭文件,而不是文檔.. – mangerlahn

+0

@Max高興地幫助:) – Hamish