您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

CoreText 實戰(三):把文字真正畫出來

編輯:iOS 開發綜合

前面聊了段落樣式,這一篇終於要動手繪製了。CoreText 畫文字的流程是固定的七步,記熟之後基本就是排列組合。

一、繪製的七個步驟

1. 獲取上下文;
2. 翻轉坐標系;
3. 建立 NSAttributedString;
4. 依 NSAttributedString 建立 CTFramesetterRef;
5. 建立繪製區域 CGPathRef;
6. 依 CTFramesetterRef 與 CGPathRef 建立 CTFrame;
7. 呼叫 CTFrameDraw 繪製。

二、字符屬性一覽

(1)//字體形狀屬性 必須是CFNumberRef 默認為0,非0則對應相應的字符形狀定義,如1表示傳統字符形狀
const CFStringRef kCTCharacterShapeAttributeName;
(2)//字體屬性 必須是CTFont對象
const CFStringRef kCTFontAttributeName;
(3)//字符間隔屬性 必須是CFNumberRef對象
const CFStringRef kCTKernAttributeName;
(4)//是否使用連字屬性 設為0表示不使用。標準英文連字有 FI、FL,默認值為1,即使用標準連字
const CFStringRef kCTLigatureAttributeName;
(5)//字體顏色屬性 必須是CGColor對象 默認為黑色
const CFStringRef kCTForegroundColorAttributeName;
(6)//是否使用上下文字體顏色 必須為CFBooleanRef 默認為False
const CFStringRef kCTForegroundColorFromContextAttributeName;
(7)//段落樣式屬性 必須是CTParagraphStyle對象 默認為NIL
const CFStringRef kCTParagraphStyleAttributeName;
(8)//筆畫線條寬度 必須是CFNumberRef對象 默認為0.0f
const CFStringRef kCTStrokeWidthAttributeName;
(9)//筆畫顏色屬性 必須是CGColorRef對象 默認為前景色
const CFStringRef kCTStrokeColorAttributeName;
(10)//上下標屬性 必須是CFNumberRef對象 默認為0,-1為下標,1為上標,需要字體支持
const CFStringRef kCTSuperscriptAttributeName;
(11)//下劃線顏色屬性 必須是CGColorRef對象 默認為前景色
const CFStringRef kCTUnderlineColorAttributeName;
(12)//下劃線樣式屬性 必須是CFNumberRef對象 默認為kCTUnderlineStyleNone
const CFStringRef kCTUnderlineStyleAttributeName;
(13)//字形方向屬性 必須是CFBooleanRef 默認為false(水平),true為豎直
const CFStringRef kCTVerticalFormsAttributeName;
(14)//字體信息屬性 必須是CTGlyphInfo對象
const CFStringRef kCTGlyphInfoAttributeName;
(15)//CTRun 委托屬性 必須是CTRunDelegate對象
const CFStringRef kCTRunDelegateAttributeName

三、常見屬性的設定寫法

準備一段可變屬性字串:

NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:@"This is a test of characterAttribute. 中文字符"];

指定字體:

CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);
[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

斜體(借系統斜體的字體名):

CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 14, NULL);
[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

下劃線:

[mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];

下劃線顏色:

[mabstring addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 4)];

字元間距:

long number = 10;
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
[mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)];

沿用上下文顏色:

CFBooleanRef flag = kCFBooleanTrue;
[mabstring addAttribute:(id)kCTForegroundColorFromContextAttributeName value:(id)flag range:NSMakeRange(5, 10)];

空心字(描邊)及描邊顏色:

long number = 2;
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
[mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])];
[mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])];

四、繪製一段純文字

建立一個繼承自 UIView 的類別,在 drawRect: 裡完成全部工作。這裡順手把繪製路徑設成橢圓,可以看到文字會沿著邊界被裁切。

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    // 步驟1:取得當前繪聲畫布的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 步驟2:翻轉坐標系(底層繪聲引擎以左下角為原點)
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    // 步驟3:建立NSAttributedString
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"iOS程序在啟動時會創建一個主線程,而在一個線程只能執行一件事情,如果在主線程執行某些耗時操作,例如加載網絡圖片,下載資源文件等會阻塞主線程(導致界面卡死,無法交互),所以就需要使用多線程技術來避免這類情況。iOS中有三種多線程技術 NSThread,NSOperation,GCD,這三種技術是隨著IOS發展引入的,抽象層次由低到高,使用也越來越簡單。"];
    // 步驟4:建立CTFramesetterRef
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
    // 步驟5:建立繪製區域CGPathRef
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddEllipseInRect(path, NULL, self.bounds);
    [[UIColor redColor]set];
    CGContextFillEllipseInRect(context, self.bounds);
    // 步驟6:建立CTFrame
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attrString length]), path, NULL);
    // 步驟7:繪製
    CTFrameDraw(frame, context);
    // 步驟8:內存管理
    CFRelease(frame);
    CFRelease(path);
    CFRelease(frameSetter);
}

五、自訂顏色、字體與行距

把上面的骨架換成矩形路徑,再加上局部顏色、局部字體和段落樣式,就是最實用的版本了。

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    //步驟1:獲取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //步驟2:翻轉坐標系
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, self.bounds.size.height);
    CGContextConcatCTM(context, flipVertical);

    //步驟3:建立NSAttributedString
    NSMutableAttributedString* attributeString = [[NSMutableAttributedString alloc]initWithString:@"在現實生活中,我們要不斷內外兼修,幾十載的人生旅途,看過這邊風景,必然錯過那邊彩虹,有所得,必然有所失。有時,我們只有徹底做到拿得起,放得下,才能擁有一份成熟,才會活得更加充實、坦然、輕松和自由。"];
    //局部顏色
    [attributeString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(10, 10)];
    //局部字體
    CGFloat fontSize = 20;
    CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialMT", fontSize, NULL);
    [attributeString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:NSMakeRange(15, 10)];
    CFRelease(fontRef);

    // 行距等段落樣式
    CGFloat lineSpace = 10;
    CGFloat lineSpaceMax = 20;
    CGFloat lineSpaceMin = 2;
    const CFIndex kNumberOfSettings = 3;
    CTParagraphStyleSetting theSettings[kNumberOfSettings] = {
        {kCTParagraphStyleSpecifierLineSpacingAdjustment,sizeof(CGFloat),&lineSpace},
        {kCTParagraphStyleSpecifierMaximumLineSpacing,sizeof(CGFloat),&lineSpaceMax},
        {kCTParagraphStyleSpecifierMinimumLineSpacing,sizeof(CGFloat),&lineSpaceMin}
    };
    CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, kNumberOfSettings);
    [attributeString addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)theParagraphRef range:NSMakeRange(0, attributeString.length)];
    CFRelease(theParagraphRef);

    //步驟4:建立CTFramesetterRef
    CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeString);
    //步驟5:建立繪製區域CGPathRef
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGPathAddRect(pathRef, NULL, CGRectInset(self.bounds, 0, 20));
    //步驟6:建立CTFrame
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0, [attributeString length]), pathRef, NULL);
    //步驟7:繪製
    CTFrameDraw(frameRef, context);
    //內存管理
    CFRelease(frameRef);
    CFRelease(pathRef);
    CFRelease(framesetterRef);
}

幾個實作心得:翻轉坐標系這一步不能省,否則文字會上下顛倒;CGPath 決定排版範圍,換成不同形狀就能做出各異的排版效果;CFRelease 對應每一個 Create,忘了就是洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved