Skip to content

Instantly share code, notes, and snippets.

@chockenberry
Last active October 22, 2020 19:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chockenberry/3e6b044192b864a10d541a6431b1f84d to your computer and use it in GitHub Desktop.
Save chockenberry/3e6b044192b864a10d541a6431b1f84d to your computer and use it in GitHub Desktop.
// UIFont+CharacterWidth.m
- (CGFloat)characterWidth
{
CGFloat characterWidth = 0.0;
// get the width of a character by doing a layout with two spaces and measuring the position of the second glyph
NSAttributedString *measureAttributedString = [[NSAttributedString alloc] initWithString:@" " attributes:@{ NSFontAttributeName: self }];
CTLineRef lineRef = CTLineCreateWithAttributedString((CFAttributedStringRef)measureAttributedString);
CFArrayRef arrayRef = CTLineGetGlyphRuns(lineRef);
CTRunRef runRef = CFArrayGetValueAtIndex(arrayRef, 0);
CGPoint *positions = (CGPoint *)CTRunGetPositionsPtr(runRef);
CFIndex count = CTRunGetGlyphCount(runRef);
if (count == 2) {
characterWidth = positions[1].x;
}
CFRelease(lineRef);
return characterWidth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment