今天蛋疼,突然想用下漂亮的字体,就稍微用研究了一下这个用法,很简单,就三步吧
1.第一步找到你想用的字体的 ttf 格式。加入到你的工程的resouce目录下。
2.在工程的plist中AddRow,“Fonts provided by application” ,然后添加key为item0,value为你刚才加入的testFont.ttf
((UIAppFonts会自动转换成Fonts provided by application,此类型为Array或Dictionary都行)。
是这样,可以添加多个,使用的时候写对应字体名字就行。
3.在你的工程就可以直接用了。xx.font = [UIFont fontWithName:@"testFont" size:20.0];
注意:
在程序中先加入这段代码,运行,
NSArray *familyNames =[[NSArray alloc]initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
NSLog(@"[familyNames count]===%d",[familyNames count]);
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]);
}
[fontNames release];
}
[familyNames release];
查看console,以上程式会列出所有的字型,当然也包含“Fonts provided by application”所加的字型,但请注意,名字可能差距很大,要自己找一下
例:
testFont.ttf , 加入Fonts provided by application
执行以上程式会列出
- 2012-10-20 21:56:21.321 MyAnimationTest[5397:c07] Family name: HAKUYOGuiFanZi3500
- 2012-10-20 21:56:21.321 MyAnimationTest[5397:c07] Font name: HAKUYOGuiFanZi3500
- 2012-10-20 21:56:21.322 MyAnimationTest[5397:c07] Family name: Didot
- 2012-10-20 21:56:21.322 MyAnimationTest[5397:c07] Font name: Didot-Italic
- 2012-10-20 21:56:21.322 MyAnimationTest[5397:c07] Font name: Didot
- 2012-10-20 21:56:21.323 MyAnimationTest[5397:c07] Font name: Didot-Bold
- 2012-10-20 21:56:21.323 MyAnimationTest[5397:c07] Family name: Bodoni 72 Smallcaps
- 2012-10-20 21:56:21.323 MyAnimationTest[5397:c07] Font name: BodoniSvtyTwoSCITCTT-Book
注意还有一个重要的是: 在“Copy Boundle Resources”中加入刚才添加的字体文件xxx.ttf ,如下:
最好直接使用就ok了。
效果 :
你可以在http://www.webpagepublicity.com/free-fonts.html下载更多ttf字体。
现在网上一般下的中文字体文件都是ttc格式的,这个需要转换一下,网上有很多转换工具,不过都是windows下面的。(ttc就是多个ttf压在一起形成的)
======================================
方法二:
直接使用代码来获取UIFont
-(UIFont*)customFont
{// 你的字体路径
NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"Amelia BT" ofType:@"ttf"];
NSURL *url = [NSURL fileURLWithPath:fontPath];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
if (fontDataProvider == NULL) return nil;
CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);
if (newFont == NULL) return nil;
NSString *fontName = (__bridge NSString *)CGFontCopyFullName(newFont);
UIFont *font = [UIFont fontWithName:fontName size:12];
CGFontRelease(newFont);
return font;
}
修正:
1.方法二中如果要使用UIFont,那么 不添加 Fonts provided by application项是不可以的。如果仅仅使用
CGFontRef,那么可以不添加。 2.测试中没有一次用ttc提取的ttf成功改变字体(中文的),但是下载的源文件就是ttf的都成功更改了字体。