开发者

Dealing with points or pixels when using UIFont

I was trying to position a string in the vertical center of a CGRect in my drawRect:(CGRect) method.

The CGRect has this size:

CGRect rect = CGRectMake(0.0f, 0.0f, rectWidth, rectHeight);

To draw the string so that开发者_JAVA百科 it is centered I tried this first:

CGFloat diffHeightRectAndFont = rectHeight - font.capHeight;
[str drawAtPoint:CGPointMake(0.0f, diffHeightRectAndFont * 0.5f) withFont:font];

This I first assumed would find the difference in height between my rect and font, then offsetting the font by half this height should give a y position in the "sweet spot".

However, the capHeight is in points and the rectHeight in pixels, so this solution kind of worked for fonts in the size range 12-15. After that the difference started to position the string outside the rect.

I went over this a few times and the only way to consistently position the string correctly turned out to be this 'hack', which is valid but does not do wonders for the readability of the code:

CGFloat diffHeightRectAndFont = rectHeight - [[NSString stringWithString:@"F"] sizeWithFont:font].height;

Is there a more direct way of obtaining the pixel height of a capital letter using a specific font?

Thank you in advance:)


I know its a bit late. but nevertheless my answer my help someone else.

NSString has a sizeWithFont: method (documented here) that I think can be used for this. It returns a CGSize structure, so you could do something similar to the following to find the height of the text inside your label.

CGSize textSize = [[label text] sizeWithFont:[label font]];

CGFloat heightOfStringWithSpecifiedFont = textSize.height;

UILabel has a font property that you can use to dynamically get the font details for your label as I'm doing above.

Hope this helps :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜