问题
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:

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

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

**How can i get get the glyph only centered in the frame ? **
Thanks
Shani
回答1:
There are a lot of properties on UIFont to help in this situation:
pointSize
ascender
descender
capHeight
xHeight
lineHeight
回答2:
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.
回答3:
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;
}
来源:https://stackoverflow.com/questions/9020246/ios-get-the-real-height-of-a-letter