Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Perkin

macrumors newbie
Original poster
Oct 22, 2013
16
0
I want to get the font traits - specifically Bold/Italic - from a ttf or otf file.
I currently have the following code
Code:
        NSURL *fontURL = [NSURL fileURLWithPath: fontFileWithFullPath];
        
        CFArrayRef fontDescription = CTFontManagerCreateFontDescriptorsFromURL ( (CFURLRef) fontURL );
        NSDictionary *fontDesc= [(__bridge NSArray *)fontDescription objectAtIndex:0];
        
        NSString* fontName = [fontDesc objectForKey:@"NSFontNameAttribute"];
        NSString* familyName = [fontDesc objectForKey:@"NSFontFamilyAttribute"];
        id fontTraits = [fontDesc objectForKey:@"NSFontTraitsAttribute"];

        NSLog(@"%@ -> %@ -> %@", fontName, familyName, fontTraits);

No matter what file I send (fontFileWithFullPath) the fontTraits is always null.

I don't want to install the font, as I'm just examining a folder of fonts (could be hundreds) and displaying the info, but just can't seem to get the bold/italic font traits.

Any ideas?
 
Debugging / diagnostic suggestions:
1. Print the value of fontFileWithFullPath.
2. Run a test with some known bold and italic files from the OS.
3. Post the output.


Rules of Thumb:
1. Post your code.
2. Describe what you expected to happen.
3. Describe what actually happened.
4. Be specific and accurate.

You did 1, except we don't know what font-files it ran on.

2 was implied by the NSLog in the code. We still don't know what font-files it was done on.

3 was only partly described ("it's null"), but the other things printed by NSLog were missing.

4 was incomplete: no list of inputs, no actual outputs.
 
SOLVED :eek:

DOH!

I had the wrong key values (putting key in a string - :eek:), change to following and it works as expected.
Code:
        NSString* fontName = [fontDesc objectForKey:NSFontNameAttribute];
        NSString* familyName = [fontDesc objectForKey:NSFontFamilyAttribute];

        NSDictionary* fontTraits = [fontDesc objectForKey:NSFontTraitsAttribute];
        NSNumber* slantTrait = [fontTraits objectForKey:NSFontSlantTrait];
        NSNumber* weightTrait = [fontTraits objectForKey:NSFontWeightTrait];
        
        NSString* fontstyle  = ( [slantTrait floatValue] >0 ? @"italic" : @"normal");
        NSString* fontweight = ([weightTrait floatValue] >0 ? @"bold" : @"normal");

        NSLog(@"%@ -> %@ -> %@", familyName, fontstyle, fontweight);
Yes I'm taking wide range of value for bold/italic (any > 0 value).
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.