Swift 把绳子拉到卷帘里
出于动画的原因,我必须将NSString绘制到CALayer对象中。这就是为什么我不能使用CATextLayer 问题是我无法在屏幕上看到文本。 我知道我必须在graphicsContext中绘制,这是在drawInContext()中移交的。我不知道如何用CGContext实例创建NSGraphicsContext实例。不推荐使用GraphicsContextWithGraphicsSport类方法。有替代品吗 注意:我正在使用Swift。您现在可以使用初始化器 因此,例如,如果您正在子类化Swift 把绳子拉到卷帘里,swift,macos,cocoa,core-graphics,Swift,Macos,Cocoa,Core Graphics,出于动画的原因,我必须将NSString绘制到CALayer对象中。这就是为什么我不能使用CATextLayer 问题是我无法在屏幕上看到文本。 我知道我必须在graphicsContext中绘制,这是在drawInContext()中移交的。我不知道如何用CGContext实例创建NSGraphicsContext实例。不推荐使用GraphicsContextWithGraphicsSport类方法。有替代品吗 注意:我正在使用Swift。您现在可以使用初始化器 因此,例如,如果您正在子类化C
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
}
委托实现将是相同的。您完全正确!非常感谢你!我应该查看头文件而不是文档。@Max乐于帮助:)