您的位置:首页 > 移动开发

给app添加新字体

2015-11-30 14:51 399 查看
在开发中,有时系统默认的字体不能满足我们的需求,那么我们就需要自己添加新的字体,字体可以在网上搜到很多,格式一般为XXX.ttf 或者 XXX.TTF.

我们将一个下载好的字体导入到Xcode工程中,注意一定要加入到Copy Bundle Resources中。

然后在info.plist中添加Array属性Fonts provided by application,并将自定义的字体的文件名(如XXX.ttf)加入到该属性下

UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 40, 300, 300)];
label.text = @"我就是测试";
label.font = [UIFont fontWithName:@"ShiShangZhongHeiJianTi" size:20];
label.textColor = [UIColor orangeColor];
[self.view addSubview:label];


直接用fontWithName调用即可。

需要注意的是,我们从网上下载的字体的文件名有时候不一定是字体的名字,即fontName。

那么我们只能自己从所有的字体中找到你添加的字体,这个过程比较纠结。我用的下面的方法遍历的,把自己添加的字体fontName打印出来。

//    系统自带的字体
NSString * path = [[NSBundle mainBundle]pathForResource:@"SystemFont" ofType:@"plist"];
NSDictionary * dic = [[NSDictionary alloc]initWithContentsOfFile:path];
NSMutableArray * fontArray = [[NSMutableArray alloc]init];
for (id value in [dic allValues]) {
[fontArray addObject:value];
}
//    所有字体(包括自己添加的字体)
NSArray *familyNames =[[NSArray alloc]initWithArray:[UIFont familyNames]];
NSInteger  fontCount;
NSLog(@"所有字体的组数共:%d组",familyNames.count);
NSMutableDictionary * fontDic = [[NSMutableDictionary alloc]init];
NSString * docPath = NSHomeDirectory();
docPath = [docPath stringByAppendingString:@"/Documents/FontNames.plist"];
for(fontCount = 0;fontCount < [familyNames count];fontCount++)
{
[fontDic setObject:familyNames[fontCount] forKey:[NSString stringWithFormat:@"%d",fontCount]];
if (![fontArray containsObject:familyNames[fontCount]]) {
NSLog(@"开发者自己添加的字体fontName为:%@",familyNames[fontCount]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: