Search code examples
objective-cbounding-boxnslayoutmanager

Get Bounding Rectangle of String with NSLayoutManager


I have a large amount of unique strings for which I want to compute their bounding rectangle when they would be laid out in an infinitly large rectangle. Currently I use a single NSTextStorage/NSLayoutManager and loop over all strings, collecting the rectangles:

// setup NSTextStorage and its NSLayoutManager, NSTextContainer
...

forall (NSAttributedString *astring in ...)
{
    // put string into textstorage
    [textStorage setAttributedString:astring];

    // trigger glyph generation and layout
    [textContainer setContainerSize: NSMakeSize (CGFLOAT_MAX, CGFLOAT_MAX)];
    [layoutManager ensureLayoutForTextContainer: textContainer];

    // finally get the bounding box
    NSRect boundingBox = [layoutManager usedRectForTextContainer: textContainer];
    ...
}

The question is: is it possible to speed up the computation considering that the strings don't need to be drawn? I'm only interested in the rectangle's width and height.


Solution

  • Jut answering this myself after a few days of testing: no, unfortunately there is no faster way using layout-managers. Using CoreText seems too be about twice as fast, but CoreText has some nasty problems itself.