Last active
October 22, 2020 19:26
-
-
Save chockenberry/3e6b044192b864a10d541a6431b1f84d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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