现在的位置: 首页 > 综合 > 正文

IOS(xcode)程序中使用自定义字体的方法

2016年09月14日 ⁄ 综合 ⁄ 共 1344字 ⁄ 字号 评论关闭

1,添加对应的字体(.ttf或.odf)到工程的resurce,例如simkai.ttf

  2,在info.plist中添加一项 Fonts provided by application (item0对应的value为simkai.ttf,添加多个字体依次添加就可以了)

  3,使用时 aLabel.font=[UIFont fontWithName:@"XXX" size:30]; 注意XXX不一定是simkai,这里是KaiTi_GB2312(中文楷体),你可以通过下面的方法遍历所有字体

  以下是代码片段:

  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]);
 	}
 	[fontNames release];
    }
    [familyNames release];

在程序中先加入这段代码,运行,查看console,以上程式会列出所有的字型,当然也包含UIAPPFonts所加的字型,但请注意,名字可能差距很大,要自己找一下

例:

      msjh.ttf   (Window7中的微软正黑体)  , 加入UIAPPFonts


       执行以上程序会列出

       Family name: Microsoft JhengHei

                Font name: MicrosoftJhengHeiRegular


要使用字体fontWithName:用“Family name”或者“Font name”都可以。

而不是字体的文件名,弄错了将无法看到效果。

在你的项目里要用字体的时候 xx.font = [UIFont fontWithName:@"Microsoft JhengHei" size:20.0],这样就可以了。

 

  其中添加的simkai.ttf对应的字体就是KaiTi_GB2312

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 50)];

  label.font = [UIFont fontWithName:@"KaiTi_GB2312" size:30];

  label.text = @"中文楷体";

  [self.view addSubview:label];

  [label release];

抱歉!评论已关闭.