Created
April 17, 2025 08:30
-
-
Save jacobsapps/24ec919f443a4e15d8c2f1e48feca7be to your computer and use it in GitHub Desktop.
Font Hacking
This file contains hidden or 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
import CoreText | |
func rollFontString(string: String) -> NSAttributedString { | |
let primaryFont = TextStyle.sfCompact.uiFont | |
let fallbackFont = UIFont.systemFont(ofSize: 14, weight: .medium) | |
let attributedString = NSMutableAttributedString(string: string, attributes: [ | |
.kern: 1, | |
.font: primaryFont, | |
]) | |
let ctFont = CTFontCreateWithName(primaryFont.fontName as CFString, primaryFont.pointSize, nil) | |
string.enumerateSubstrings(in: string.startIndex ..< string.endIndex, options: .byComposedCharacterSequences) { substring, substringRange, _, _ in | |
let uniChar = UniChar(substring.unicodeScalars.first.value) | |
var glyph: CGGlyph = 0 | |
let hasGlyph = CTFontGetGlyphsForCharacters(ctFont, [uniChar], &glyph, 1) | |
if !hasGlyph { | |
attributedString.addAttribute( | |
.font, | |
value: fallbackFont, | |
range: NSRange(substringRange, in: string) | |
) | |
} | |
} | |
return attributedString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment