Search code examples
iphonedrawingcore-textnsattributedstringctlineref

CTLine or NSAttributedString -- get image bounds without a graphics context?


Is this possible? Basically, I have a bunch of NSAttributedString objects and corresponding CTLine objects. I want to get the image bounds before the drawRect stage. So at this point, there is nothing to draw into. I will then use these image bounds to decide exactly what I need to create for drawing.

EDIT: Another measurement of the size would probably work just fine. But calling the deceptively named CTLineGetTypographicBounds function only returns the width. If I pass in addresses of ascent and descent floats, they come back as zero.

EDIT: The given answer works great in MacOS. Can anyone do it in iOS?


Solution

  • If you are developing for iOS6+. You can use the following method:

    CTLineRef line;
    // Create the line...
    
    CGRect bounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds);
    // use bounds...
    

    This is gives the same bounds as CTLineGetImageBounds() assuming you have no transforms applied in your context, but does not require the context. For iOS 5 and below, you would need to use the method described by Иван.

    CTLineGetTypographicBounds() gives me a different width than this function or image bounds. I am not sure why. And the ascent and descent returned are those of the font and not the characters displayed in the CTLineRef.