Search code examples
iosobjective-cstringpositionbaseline

Objective-C - Text baseline on lower left corner


When drawing a string in IOS, by default the text is baselined by the upper left corner. This can cause problems when using multiple strings with different font-sizes with the same y-coordinate.

Question;
How do I baseline a string by the lower left corner of the first row.

enter image description here

How do I achieve this?

Br,
Tim


Solution

  • I finally found the solution to my problem.
    By subtracting the UIFont ascender property from the rect.origin.y, I could baseline the text to the lower left corner.

    Citing the UIFont documentation of the ascender property:

    "The top y-coordinate, offset from the baseline, of the receiver’s longest ascender." https://developer.apple.com/library/ios/documentation/uikit/reference/UIFont_Class/Reference/Reference.html#//apple_ref/occ/instp/UIFont/ascender

    - (void)drawTextBaseLined:(NSString *)text
                         rect:(CGRect)rect
                         font:(UIFont *)font
    {
      if ([text length] == 0) return false;
    
      NSDictionary *attributes = @{NSFontAttributeName : font};
    
      rect.origin.y -= font.ascender;
      [text drawWithRect:rect
                 options:NSStringDrawingUsesLineFragmentOrigin
              attributes:attributes
                 context:nil];
    }
    

    This method will work with one or multiple lines of text and with different font-sizes. I hope my solution helps someone else too.

    Br,
    Tim