问题
In my iOS app I use custom fonts, dynamically loaded from files.
To use them in code, I need to know loaded fonts' families. So, is there any way to do it?
UPDATE:
I can't somehow hardcode font families, cause my app loads it from server. Of course, there is a way to pass font families in server response, but for now I'm looking for a better version that doesn't influence the server (doesn't need to change it).
回答1:
Font loading I did...
NSData *fontData = [NSData dataWithContentsOfFile:filePath];
if (fontData) {
// create font from loaded data and get it's postscript name
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithCFData((CFDataRef)fontData);
CGFontRef loadedFont = CGFontCreateWithDataProvider(fontDataProvider);
NSString *postScriptName = (NSString *)CGFontCopyPostScriptName(loadedFont);
// if the font with same postscript name wasn't already registered - do it
if (postScriptName && ![UIFont fontWithName:postScriptName size:10]) {
NSError *error;
if (!CTFontManagerRegisterGraphicsFont(loadedFont, (CFErrorRef *)&error)) {
NSLog(@"Can't load font: %@", error);
}
}
CGFontRelease(loadedFont);
CGDataProviderRelease(fontDataProvider);
}
回答2:
In the docs see the section called Getting the Available Font Names. You can list all family names, and individual font names of the family you want. I usually just pause the debugger and call the functions myself from the command line. It is the safest way to get the name that iOS will use. Or are you talking about downloading fonts and loading them? That will require more than just knowing their names.
EDIT Ok, then you are downloading fonts. In that case, you will have to drop into the world of Core Text. See this reference to get started (pay attention to the functions called "register font"). If you successfully register it, then it will show up using the above methods.
回答3:
I got this code from somewhere on stack overflow. Hope it helps. It lists all the loaded font names...
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily) {
NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
fontNames = [[NSArray alloc] initWithArray:
[UIFont fontNamesForFamilyName:
[familyNames objectAtIndex:indFamily]]];
for (indFont=0; indFont<[fontNames count]; ++indFont) {
NSLog(@" Font name: %@", [fontNames objectAtIndex:indFont]);
}
}
来源:https://stackoverflow.com/questions/14824828/get-font-face-from-ttf-file