cocoacalayernslayoutmanagernstextstorage

How to render text in a CALayer using NSLayoutManager?


I am using the trio of NSLayoutManager, NSTextStorage & NSTextContainer to render text in a layer-backed NSView.

I am under the impression that the view will be more performant if I can override wantsUpdateLayer to return true and thus be using layers more fully. Is this true?

However, all examples I have seen of using NSLayoutManager say that you need to place the following call within drawRect:

layoutManager.drawGlyphsForGlyphRange(glyphRange, atPoint: NSMakePoint(0, 0)) 

How would you perform the equivalent call within updateLayer or some other more layer-oriented place instead?


Solution

  • I created a custom CALayer and overrode the drawInContext method as below:

    override func drawInContext(ctx: CGContext!) {
        NSGraphicsContext.saveGraphicsState()
    
        var nsgc = NSGraphicsContext(CGContext: ctx, flipped: false)
        NSGraphicsContext.setCurrentContext(nsgc)
    
        NSColor.whiteColor().setFill()
        NSRectFill(NSMakeRect(0, 0, 84, 24))
    
        lm.drawGlyphsForGlyphRange(glyphRange, atPoint: NSMakePoint(0, 0))  // location of textContainer
    
        NSGraphicsContext.restoreGraphicsState()
    
    }
    

    This gets the job done, but

    1. I'm not sure if there are any performance implications to saving and restoring the graphics context as above.
    2. I am unsure how the same would be achieved in the NSView's updateLayer method as that does not have a context to use.