Based on the response I received to my last post about Custom Fonts on the iPad and iOS 4, iOS font handling and Core Text are a bit of a mystery to many iOS developers. Because of that, I’ll focus on Core Text for my next few #idevblogaday posts. This week, the spotlight is on loading and configuring fonts to be drawn with Core Text or CATextLayer.
Registering Custom Fonts With iOS
Last week, I explained how to load a font directly from a file using Quartz data providers. While this is a perfectly acceptable way to load a custom font, it is no longer necessary. In iOS 3.2, a new key was added to Info.plist called UIAppFonts (special thanks to @hanspinckaers and Ilari Sani for reminding me it exists). This little gem takes an array of font file names, and it makes the named fonts available through the normal font loading mechanism. This means you can finally use Comic Sans instead of Marker Felt in your apps.
Using UIAppFonts is very simple. First, you need to make sure your font files are in your app bundle. Then, add the UIAppFonts key to your Info.plist, and add an entry in the array for each font file you want available to your app.
Provided your font is one of the supported font types, it should now be available to load like any system font. The following line of code uses Core Text to load our font:
CTFontRef canHazComicSans = CTFontCreateWithName(CFSTR("ComicSans"), 24.f, NULL);
Next Week: Configuring Font Attributes
Core Text fonts are very configurable. The power lies in CTFontDescriptor, and it will be our topic next week. Here’s a little code teaser to whet your appetite:
NSDictionary *fontAttributes = [NSDictionary dictionaryWithObjectsAndKeys: @"Courier", (NSString *)kCTFontFamilyNameAttribute, @"Bold", (NSString *)kCTFontStyleNameAttribute, [NSNumber numberWithFloat:16.f], (NSString *)kCTFontSizeAttribute, nil]; CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)attributes); CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, 0, NULL); CFRelease(descriptor);
See you next week!
P.S. – If you actually want to see me in person next week, I’ll be giving a half day workshop on Core Animation as well as a shorter talk about drawing with Quartz in UIKit at the iPhone/iPad DevCon in San Diego. Hopefully I’ll see you there!