1. 動態下載系統提供的中文字體html
- 字體文件比較大,會形成應用體積劇增
- 中文字體一般都是有版權的
動態下載中文字體的API能夠動態的向iOS系統中添加字體文件,這些字體文件都是下載到系統的目錄中,因此不會形成應用體積增長,字體文件下載後還能夠在全部應用間共享。而且字體文件是iOS系統提供的,也免去了字體使用版權的問題ios
下載的時候須要使用的名字是 PostScript 名稱,因此你要動態下載相應的字體的話,還須要使用 Mac 內自帶的應用 「字體冊 「來得到相應字體的 PostScript 名稱。以下顯示了從」 字體冊 「中獲取字體的 PostScript 名稱的截圖git
蘋果提供的動態下載代碼的 Demo 工程 連接在這裏。將此 Demo 工程下載下來,便可學習相應 API 的使用github
// 1. 先判斷該字體是否已經被下載下來了
- (BOOL)isFontDownloaded:(NSString *)fontName {
UIFont* aFont = [UIFont fontWithName:fontName size:12.0];
if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame
|| [aFont.familyName compare:fontName] == NSOrderedSame)) {
return YES;
} else {
return NO;
}
}
// 2. 若是該字體下載過了,則能夠直接使用。不然須要先準備下載字體 API 須要的一些參數
// 用字體的 PostScript 名字建立一個 Dictionary
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];
// 建立一個字體描述對象 CTFontDescriptorRef
CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);
// 將字體描述對象放到一個 NSMutableArray 中
NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
[descs addObject:(__bridge id)desc];
CFRelease(desc);
// 3. 準備好上面的descs變量後,則能夠進行字體的下載了
__block BOOL errorDuringDownload = NO;
CTFontDescriptorMatchFontDescriptorsWithProgressHandler((CFArrayRef)descs, NULL, ^bool(CTFontDescriptorMatchingState state, CFDictionaryRef _Nonnull progressParameter){
double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
if (state == kCTFontDescriptorMatchingDidBegin) {
NSLog(@" 字體已經匹配 ");
} else if (state == kCTFontDescriptorMatchingDidFinish) {
if (!errorDuringDownload) {
NSLog(@" 字體 %@ 下載完成 ", fontName);
}
} else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
NSLog(@" 字體開始下載 ");
} else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
NSLog(@" 字體下載完成 ");
dispatch_async( dispatch_get_main_queue(), ^ {
// 能夠在這裏修改 UI 控件的字體
// self.label.font = [UIFont fontWithName:fontName size:12];
});
} else if (state == kCTFontDescriptorMatchingDownloading) {
NSLog(@" 下載進度 %.0f%%", progressValue);
} else if (state == kCTFontDescriptorMatchingDidFailWithError) {
NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
if (error != nil) {
_errorMessage = [error description];
} else {
_errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
}
// 設置標誌
errorDuringDownload = YES;
NSLog(@" 下載錯誤: %@", _errorMessage);
}
return YES;
});
複製代碼
2. 導入TTF字體文件使用自定義字體bash
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 400)];
label.text = @"漢體書寫信息技術標準相容檔案下載使用界面簡單";
label.numberOfLines = 0;
UIFont *font = [UIFont fontWithName:@"FZLTXHK--GBK1-0" size:40];
[self.view addSubview:label];
複製代碼
附:個人博客地址app