On an iPhone how do I calculate the size of a character in pixels for a given point size?
On an iPhone how do I calculate the size of a character in pixels for a given point size?
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.
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;
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
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;
}
You can calculate the pixel size on the fly by rendering a NSAttributedString and getting its size.
extension UIFont {
var pixelSize: CGFloat {
let string = "AWZgjpq"
let attributedString = NSMutableAttributedString(string: string)
attributedString.setAttributes([.font: self], range: NSRange(location: 0, length: string.count))
return attributedString.size().height
}
}
Further optimizations could be to add a lookup dictionary and cache results and/or make the test string not a variable (but the call itself is really fast). Also, if your font has some very irregular glyphs you can add them to the test string as well.
Usage: let pixelSize = label.font.pixelSize