Ok, I figured it out. The following code gives me the correct bounds of the attributed string:
- (CGRect)typographicBounds
{
CGRect usedRect = CGRectZero;
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)self);
if (line) {
CGContextRef context = [[NSGraphicsContext currentContext] CGContext];
usedRect = CTLineGetImageBounds(line, context);
CFRelease(line);
}
return usedRect;
}
and the following code draws it exactly into the view:
NSRect stringRect = [_attributedString typographicBounds];
// draw the string
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)_attributedString);
if (line) {
CGContextRef context = [[NSGraphicsContext currentContext] CGContext];
CGContextSetTextPosition(
context,
((NSWidth([self frame]) - NSWidth(stringRect)) / 2) - stringRect.origin.x,
((NSHeight([self frame]) - NSHeight(stringRect)) / 2) - stringRect.origin.y
);
CTLineDraw(line, context);
CFRelease(line);
}
@DTS Engineer Thank you for your patience and for showing me the right direction.