(轉載)教你如何在iOS項目中設置各種字體

原文地址:http://www.cnblogs.com/jijiYY/p/4736967.html
在iOS開發(fā)中設置字體的方法有很多種,下面為大家介紹比較常用的三種方法
1.使用系統(tǒng)默認提供的字體
系統(tǒng)默認提供的字體主要是指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設置字體,但是全部是只針對英文數(shù)字,對中文無效。要想改變中文字體還需要使用后面兩種辦法

2.動態(tài)下載字體

iOS6以后蘋果就開始支持動態(tài)下載中文字體已供應用中展示個性字體的需求,由于下載的時候需要使用的名字是PostScript名稱,需要使用Mac內(nèi)自帶的應用“字體冊“來獲得相應字體的PostScript名稱。如下顯示了從”字體冊“中獲取《娃娃體-繁 常規(guī)體》字體的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 downloaded
    if (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:(__bridge id)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);
        
        double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
        
        if (state == kCTFontDescriptorMatchingDidBegin) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Show an activity indicator
                NSLog(@"Begin Matching");
            });
        } else if (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 console
                CTFontRef 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);
                }
            });
        } else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Show a progress bar
             
                NSLog(@"Begin Downloading");
            });
        } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Remove the progress bar

                NSLog(@"Finish downloading");
            });
        } else if (state == kCTFontDescriptorMatchingDownloading) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                // Use the progress bar to indicate the progress of the downloading
                NSLog(@"Downloading %.0f%% complete", progressValue);
            });
        } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
            // An error has occurred.
            // Get the error message
            NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
            if (error != nil) {
                _errorMessage = [error description];
            } else {
                _errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
            }
            // Set our flag
            errorDuringDownload = YES;
            
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"Download error: %@", _errorMessage);
            });
        }
        return (bool)YES;
    });   
}

只要在相應地方調(diào)用就可以了:

- (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.引入外部字體

現(xiàn)在網(wǎng)上不管是windows字體,還是Android字體只要是ttf格式的,或者是蘋果提供的ttc、otf格式,一般iOS程序都支持內(nèi)嵌。具體做法:
先將需要下載的字體拖到項目中


在info文件中添加相應字段

然后就可以使用上面提供的方法[UIFont fontWithName:@"迷你簡咪咪" size:17]方法給英文、數(shù)字或者中文設置上這種字體??梢暂敵鲆幌耓UIFont familyNames]檢測是否已經(jīng)添加

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

網(wǎng)上下載的字體也不一定都是可以使用,下面提供大家一些常用字體供大家下載:
鏈接: http://pan.baidu.com/s/1kTVX8qF 密碼: vdwa
要想獲取更加全面的字體還可以使用蘋果自己提供的各種字體格式,還是可以通過Mac應用“字體側”獲取,例如:


用法跟下載的字體一樣

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 在iOS開發(fā)中設置字體的方法有很多種,下面為大家介紹比較常用的三種方法 1.使用系統(tǒng)默認提供的字體 系統(tǒng)默認提供的...
    默默_David閱讀 10,050評論 0 2
  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,083評論 4 61
  • 盡量去認識世界的真實性,因為你不能一直生活在一個想象的世界里。 真實地活,讓我們更賦有活力。 今天晨...
    丁香的故事閱讀 274評論 0 0
  • 魯先圣,中國作家協(xié)會會員,教育部十一五課題組文學專家,中國書畫藝術研究院山東分院副院長,魯先圣書院院長,《持續(xù)地敲...
    魯先圣閱讀 1,783評論 2 5
  • 中午大伙聚在會議室吃飯,大伙聊到了自己第一份工作的感悟。在這些老油條面前,我參加工作的年限只能算是職場小白。 作為...
    向行閱讀 306評論 2 2

友情鏈接更多精彩內(nèi)容