shannoga
shannoga

Reputation: 19869

iOS - Get the "real" height of a letter

I am trying to layout text on a UIView.

(The yellow area is the frame of the UILabel with a background color).

When I use sizeWithFont I get this, which has a very large space above the letter:

p with sizeWithFont

When I use font.pointSize i get this for "i" which is good-

p with font.pointSize

BUT When i use it for "p" I get the precise height but the letter is drawn in the bottom and cropped.

p with font.pointSize

**How can i get get the glyph only centered in the frame ? **

Thanks

Shani

Upvotes: 14

Views: 11467

Answers (3)

Rolf Hendriks
Rolf Hendriks

Reputation: 421

Try moving the text upwards by font.ascender - font.capHeight. Shrinking the height of a UILabel will likely clip its contents, so it is better to adjust the label's y position instead of resizing.

The following code sample explains the computation I used:

// in UILabel subclass:
- (CGFloat) topPadding
{
    // ascender = height from baseline to top of label (including top padding)
    // capHeight = height of a capital letter = ascender - top padding
    //  -> top padding = ascender - capHeight
    return self.font.ascender - self.font.capHeight;
}

Upvotes: 3

Jeff Kelley
Jeff Kelley

Reputation: 19071

There are a lot of properties on UIFont to help in this situation:

  • pointSize
  • ascender
  • descender
  • capHeight
  • xHeight
  • lineHeight

Upvotes: 23

basvk
basvk

Reputation: 4546

You could convert the UILabel to a UIImage with a "printscreen" sort of function and then check the the pixels one by one (with for instance: How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?) and 'calculate' the left top en right bottom.

Upvotes: 3

Related Questions