教你如何在iOS項目中設置各種字體

在iOS開發中設置字體的方法有很多種,下面為大家介紹比較常用的三種方法

1.使用系統默認提供的字體

系統默認提供的字體主要是指UIFont中提供的字體,其使用代碼為:

fontLabel.font = [UIFont fontWithName:@"Marion"size:17];

或者是通過字體詳細字典對字體屬性進行設置

/*UIFontDescriptorFamilyAttribute:設置字體家族名

UIFontDescriptorNameAttribute? :設置字體的字體名

UIFontDescriptorSizeAttribute? :設置字體尺寸

UIFontDescriptorMatrixAttribute:設置字體形變*/UIFontDescriptor*attributeFontDescriptor =[UIFontDescriptor fontDescriptorWithFontAttributes:

@{UIFontDescriptorFamilyAttribute:@"Marion",

UIFontDescriptorNameAttribute:@"Marion-Regular",

UIFontDescriptorSizeAttribute: @40.0,

UIFontDescriptorMatrixAttribute:[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(M_1_PI*1.5)

]}];

fnotLabel.font= [UIFont fontWithDescriptor:attributeFontDescriptor size:0.0];

其中的字體家族名和字體名可以通過以下方法獲取

NSLog(@"familyNames:%@",[UIFont familyNames]);

以上兩種方法均可以為label設置字體,但是全部是只針對英文數字,對中文無效。要想改變中文字體還需要使用后面兩種辦法

2.動態下載字體

iOS6以后蘋果就開始支持動態下載中文字體已供應用中展示個性字體的需求,由于下載的時候需要使用的名字是PostScript名稱,需要使用Mac內自帶的應用“字體冊“來獲得相應字體的PostScript名稱。如下顯示了從”字體冊“中獲取《娃娃體-繁常規體》字體的PostScript名稱的截圖

具體代碼就不一一介紹了,大家可以參考蘋果提供的有關文檔:https://developer.apple.com/library/ios/samplecode/DownloadFont/Listings/DownloadFont_ViewController_m.html#//apple_ref/doc/uid/DTS40013404-DownloadFont_ViewController_m-DontLinkElementID_6

或者也可以參考唐巧先生的博客有比較詳細的介紹:http://blog.devtang.com/blog/2013/08/11/ios-asian-font-download-introduction/

下面是我研究后的測試demo,提供給大家參考:

- (void)asynchronouslySetFontName:(NSString *)fontName

{

UIFont* aFont = [UIFont fontWithName:fontName size:24];//If the font is already downloadedif(aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] ==NSOrderedSame)) {//Go ahead and display the sample text._fLabelView.text =@"歡迎查看我的博客";

_fLabelView.font= [UIFont fontWithName:fontName size:24];return;

}//Create a dictionary with the font's PostScript name.NSMutableDictionary *attrs =[NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];//Create a new font descriptor reference from the attributes dictionary.CTFontDescriptorRef desc =CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);

NSMutableArray*descs = [NSMutableArray arrayWithCapacity:0];

[descs addObject:(__bridgeid)desc];

CFRelease(desc);

__block BOOL errorDuringDownload=NO;//Start processing the font descriptor..//This function returns immediately, but can potentially take long time to process.//The progress is notified via the callback block of CTFontDescriptorProgressHandler type.//See CTFontDescriptor.h for the list of progress states and keys for progressParameter dictionary.CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL,? ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {//NSLog( @"state %d - %@", state, progressParameter);doubleprogressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];if(state ==kCTFontDescriptorMatchingDidBegin) {

dispatch_async( dispatch_get_main_queue(),^{//Show an activity indicatorNSLog(@"Begin Matching");

});

}elseif(state ==kCTFontDescriptorMatchingDidFinish) {

dispatch_async( dispatch_get_main_queue(),^{//Remove the activity indicator//Display the sample text for the newly downloaded font_fLabelView.text =@"歡迎查看我的博客";

_fLabelView.font= [UIFont fontWithName:fontName size:24];//Log the font URL in the consoleCTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName,0., NULL);

CFStringRef fontURL=CTFontCopyAttribute(fontRef, kCTFontURLAttribute);

NSLog(@"%@", (__bridge NSURL*)(fontURL));

CFRelease(fontURL);

CFRelease(fontRef);if(!errorDuringDownload) {

NSLog(@"%@ downloaded", fontName);

}

});

}elseif(state ==kCTFontDescriptorMatchingWillBeginDownloading) {

dispatch_async( dispatch_get_main_queue(),^{//Show a progress barNSLog(@"Begin Downloading");

});

}elseif(state ==kCTFontDescriptorMatchingDidFinishDownloading) {

dispatch_async( dispatch_get_main_queue(),^{//Remove the progress barNSLog(@"Finish downloading");

});

}elseif(state ==kCTFontDescriptorMatchingDownloading) {

dispatch_async( dispatch_get_main_queue(),^{//Use the progress bar to indicate the progress of the downloadingNSLog(@"Downloading %.0f%% complete", progressValue);

});

}elseif(state ==kCTFontDescriptorMatchingDidFailWithError) {//An error has occurred.//Get the error messageNSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];if(error !=nil) {

_errorMessage=[error description];

}else{

_errorMessage=@"ERROR MESSAGE IS NOT AVAILABLE!";

}//Set our flagerrorDuringDownload =YES;

dispatch_async( dispatch_get_main_queue(),^{

NSLog(@"Download error: %@", _errorMessage);

});

}return(bool)YES;? ? });? }

只要在相應地方調用就可以了:

- (void)viewDidLoad {

[super viewDidLoad];//Do any additional setup after loading the view, typically from a nib._fLabelView = [[UITextView alloc] initWithFrame:CGRectMake(50,100,250,100)];

[self.view addSubview:_fLabelView];

[self asynchronouslySetFontName:@"HanziPenSC-W3"];

}

下面是運行后的結果:

3.引入外部字體

現在網上不管是windows字體,還是Android字體只要是ttf格式的,或者是蘋果提供的ttc、otf格式,一般iOS程序都支持內嵌。具體做法:

先將需要下載的字體拖到項目中

在info文件中添加相應字段

然后就可以使用上面提供的方法[UIFont fontWithName:@"迷你簡咪咪" size:17]方法給英文、數字或者中文設置上這種字體。可以輸出一下[UIFont familyNames]檢測是否已經添加

也可以在xib中為label設置這種字體了

網上下載的字體也不一定都是可以使用,下面提供大家一些常用字體供大家下載:

鏈接: http://pan.baidu.com/s/1kTVX8qF 密碼: vdwa

要想獲取更加全面的字體還可以使用蘋果自己提供的各種字體格式,還是可以通過Mac應用“字體側”獲取,例如:

用法跟下載的字體一樣

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容