On an iPhone how do I calculate the size of a character in pixels for a given point size?
The easiest way to get the pixel height for a given font and size is to use the boundingRect method on NSString. (I'm using @"Ap"
here to make sure it contains a descender and an ascender.)
- (CGFloat)heightForFont:(UIFont *)font
{
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGRect boundingRect = [@"Ap" boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:context];
return boundingRect.size.height;
}
I believe you're looking for the UIFont
NSString
extensions that allow you to calculate the size of a string given a UIFont
.
Here is the Link
Specifically the sizeWithFont
methods.
You can't reliably convert points to pixels as the ppi (points-per-inch) will change from monitor to monitor. Have a read;
http://hsivonen.iki.fi/units/
Convert Pixels to Points
That said, some people have put together a few reference tables and calculators that may get you started;
http://www.unitconversion.org/typography/postscript-points-to-pixels-x-conversion.html
http://sureshjain.wordpress.com/2007/07/06/53/
I will add them as I figure them out:
A sizedToFit UILabel with a 12pt systemFont is 15px high.
Point sizes are defined as 1/72 of an inch. That is, a 72-point font is approximately 1 inch from the lowest descent to the highest ascent. So the maximum height of a glyph in a 72pt font is about 1 inch.
Apple's iphone tech specs page claims that the iPhone currently has a resolution of 163 pixels per inch. So 72 points is 163 pixels, or about 2.2639 pixels per point. Just remember that every glyph varies in height and width, so this is a very rough estimate of size. Generally, the distance between baselines will be a bit larger than the font's point size so that lines of text don't crash into each other.
If you need exact measurements (and you probably do) then you'll need to actually measure the font glyphs using the font metric information. You can do this by using NSString's UIKit additions, which will let you measure the size of a particular string when rendered on screen.
To match font sizes (in Points) on the iPhone4 with font sizes (in Points) in Photoshop you have to set your Photoshop document to 144dpi. I have run a number of tests and that's the resolution that produces 1:1 results.
Steps:
I have gone through a number of different resolutions, including the 163dpi that was mentioned in the answer above, and I found that 144dpi produces 1:1 results. I have also tested this against a native app where I know the point sizes and the 144dpi was match there too.