您現在可以使用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
}
的委託實現將是相同的。
你是完全正確的!非常感謝!我應該看看頭文件,而不是文檔.. – mangerlahn
@Max高興地幫助:) – Hamish