Font traits from file

Discussion in 'Mac Programming' started by Perkin, Jan 19, 2015.

  1. Perkin macrumors newbie

    Joined:
    Oct 22, 2013
    #1
    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?
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    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.
     
  3. Perkin thread starter macrumors newbie

    Joined:
    Oct 22, 2013
    #3
    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).
     

Share This Page