借助 CoreText 技術,我們能對富文本進行相當複雜的排版。經過簡單擴充,還能實現圖片、連結的點擊效果。相較於 UIWebView,CoreText 佔用記憶體更少,且能在背景執行緒渲染,非常適合用於內容排版。
本章將從最基礎的地方起步,一步步打造出一個支援圖文混排、並能處理圖片與連結點擊的排版引擎。
CoreText 是處理文字與字型的底層技術,它直接與 Core Graphics(又稱 Quartz)打交道。Quartz 是一個 2D 圖形渲染引擎,負責處理 OS X 與 iOS 上的圖形顯示。
Quartz 能直接處理字型(font)與字形(glyphs),把文字渲染到畫面上,它是基礎函式庫中唯一能處理字形的模組。因此 CoreText 為了排版,需要把要顯示的文字內容、位置、字型、字形直接交給 Quartz。由於直接與 Quartz 互動,CoreText 相較於其他 UI 元件擁有極高的排版效能。
下圖是 CoreText 的架構圖。可以看到它處於非常底層的位置,上層的 UI 控件(包含 UILabel、UITextField、UITextView)與 UIWebView 其實都是建立在 CoreText 之上。
注意:這是 iOS 7 之後的架構圖。在 iOS 7 以前並沒有圖中的 Text Kit,但 CoreText 仍是最底層、直接與 Core Graphics 互動的模組。

UIWebView 也是處理複雜排版的候選方案。相較於 UIWebView,基於 CoreText 有以下優勢:
CoreText 佔用記憶體更少、渲染更快;UIWebView 則佔用較多記憶體、渲染較慢。CoreText 在渲染前就能精確取得內容高度(只要有 CTFrame 即可),而 UIWebView 必須等內容渲染完成後才能取得高度(還得靠 JavaScript)。CoreText 的 CTFrame 能在背景執行緒渲染,UIWebView 則只能在主執行緒渲染。基於 CoreText 能做出更細膩的原生互動效果,而 UIWebView 的互動靠 JavaScript 實現,難免有些卡頓——例如一個簡單的按鈕按下效果,UIWebView 都難以做到原生的即時與細膩。
當然,CoreText 方案也有劣勢:
它渲染出的內容不像 UIWebView 那樣方便複製;而且需要自行處理大量複雜邏輯,例如圖文混排、連結點擊等,都得自己實作。
業界不少應用都採用了 CoreText 排版方案,例如新浪微博、多看閱讀等。我所在的團隊,其產品也使用自行實作的 CoreText 排版引擎,下圖是產品的圖文混排畫面(其中所有公式都以圖片呈現),可見圖文排版效果相當出色。
首先我們建立一個新的 Xcode 專案:打開 Xcode,選擇 File → New → Project,在對話框中選擇 Single View Application 後點擊 Next,接著填入專案名稱 CoreTextDemo 再點擊 Next。選擇儲存路徑後,就成功建立了一個空白專案。
圖 2

圖 3

在專案目錄 CoreTextDemo 上按右鍵選擇 New File,填入類名 CTDisplayView,並讓它的父類為 UIView。

接著在 CTDisplayView.m 中引入 CoreText/CoreText.h,並實作 drawRect 方法:
#import "CTDisplayView.h" #import "CoreText/CoreText.h" @implementation CTDisplayView - (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 CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, self.bounds); // 步驟 4 NSAttributedString *attString = [[NSAttributedString alloc] initWithString:@"Hello World!"]; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [attString length]), path, NULL); // 步驟 5 CTFrameDraw(frame, context); // 步驟 6 CFRelease(frame); CFRelease(path); CFRelease(framesetter); } @end
接著打開 Storyboard 檔 Main_iPhone.storyboard,執行兩個步驟:將一個 UIView 控件拖到主畫面正中;把該 UIView 的類名從 UIView 改為 CTDisplayView。

執行程式後,就能看到 Hello World 出現在畫面正中央。

以下說明 drawRect 的主要步驟:
取得當前繪製畫布的上下文,用於後續把內容畫上去。
將座標系上下翻轉。對底層繪製引擎而言,螢幕左下角是 (0, 0);而對上層 UIKit 而言,左上角才是 (0, 0)。為了讓之後的座標描述以 UIKit 為準,這裡先做翻轉,使上下兩層的 (0, 0) 重合。
若把這段程式碼註解掉,你會發現整個 Hello World 畫面上下顛倒。

建立繪製區域。CoreText 本身支援各種文字排版區域,這裡簡單地以整個 UIView 作為排版範圍。
若把該步驟改成用橢圓路徑,並搭配較長的文字,就能測試不同繪製區域帶來的畫面變化。
// 步驟 3 CGMutablePathRef path = CGPathCreateMutable(); CGPathAddEllipseInRect(path, NULL, self.bounds);
執行結果如下圖。

為了方便撰寫,我在 CoreTextDemo-Prefix.pch 中加入了以下基本巨集,方便使用 NSLog 與 UIColor:
#ifdef DEBUG #define debugLog(...) NSLog(__VA_ARGS__) #define debugMethod() NSLog(@"%s", __func__) #else #define debugLog(...) #define debugMethod() #endif #define RGB(A, B, C) [UIColor colorWithRed:A/255.0 green:B/255.0 blue:C/255.0 alpha:1.0]
我也為 UIView 的 frame 調整加了擴充,方便直接設定 x、y、width、height 等值:
@implementation UIView (frameAdjust) - (CGFloat)x { return self.frame.origin.x; } - (void)setX:(CGFloat)x { self.frame = CGRectMake(x, self.y, self.width, self.height); } - (CGFloat)y { return self.frame.origin.y; } - (void)setY:(CGFloat)y { self.frame = CGRectMake(self.x, y, self.width, self.height); } - (CGFloat)height { return self.frame.size.height; } - (void)setHeight:(CGFloat)height { self.frame = CGRectMake(self.x, self.y, self.width, height); } - (CGFloat)width { return self.frame.size.width; } - (void)setWidth:(CGFloat)width { self.frame = CGRectMake(self.x, self.y, width, self.height); } @end
上面的 Hello World 只是展示了 CoreText 的基本能力。要打造一個較完善的排版引擎,不能把所有程式碼都塞進 CTDisplayView 的 drawRect 裡。根據設計模式中的「單一職責原則」(Single responsibility principle),我們應該把功能拆分到各自的類別中。
一個完整的排版引擎,可以拆成:一個負責顯示的類別、一個承載資料的模型類別、一個負責排版的類別,以及一個負責可配置項的設定類別。
依此原則,我們把 CTDisplayView 拆成四個類別:
CTFrameParserConfig,配置繪製參數,例如文字顏色、大小、行距。CTFrameParser,產生最終繪製所需的 CTFrameRef。CoreTextData,保存 CTFrameParser 產生的 CTFrameRef 及實際繪製所需的高度。CTDisplayView,持有 CoreTextData,負責把 CTFrameRef 繪製到畫面上。
CTFrameParserConfig 類:
#import@interface CTFrameParserConfig : NSObject @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat fontSize; @property (nonatomic, assign) CGFloat lineSpace; @property (nonatomic, strong) UIColor *textColor; @end
#import "CTFrameParserConfig.h" @implementation CTFrameParserConfig - (id)init { self = [super init]; if (self) { _width = 200.0f; _fontSize = 16.0f; _lineSpace = 8.0f; _textColor = RGB(108, 108, 108); } return self; } @end
CTFrameParser 類:
#import#import "CoreTextData.h" #import "CTFrameParserConfig.h" @interface CTFrameParser : NSObject + (CoreTextData *)parseContent:(NSString *)content config:(CTFrameParserConfig*)config; @end
#import "CTFrameParser.h" #import "CTFrameParserConfig.h" @implementation CTFrameParser + (NSDictionary *)attributesWithConfig:(CTFrameParserConfig *)config { CGFloat fontSize = config.fontSize; CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialMT", fontSize, NULL); CGFloat lineSpacing = config.lineSpace; const CFIndex kNumberOfSettings = 3; CTParagraphStyleSetting theSettings[kNumberOfSettings] = { { kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &lineSpacing }, { kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(CGFloat), &lineSpacing }, { kCTParagraphStyleSpecifierMinimumLineSpacing, sizeof(CGFloat), &lineSpacing } }; CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, kNumberOfSettings); UIColor * textColor = config.textColor; NSMutableDictionary * dict = [NSMutableDictionary dictionary]; dict[(id)kCTForegroundColorAttributeName] = (id)textColor.CGColor; dict[(id)kCTFontAttributeName] = (__bridge id)fontRef; dict[(id)kCTParagraphStyleAttributeName] = (__bridge id)theParagraphRef; CFRelease(theParagraphRef); CFRelease(fontRef); return dict; } + (CoreTextData *)parseContent:(NSString *)content config:(CTFrameParserConfig*)config { NSDictionary *attributes = [self attributesWithConfig:config]; NSAttributedString *contentString = [[NSAttributedString alloc] initWithString:content attributes:attributes]; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)contentString); CGSize restrictSize = CGSizeMake(config.width, CGFLOAT_MAX); CGSize coreTextSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,0), nil, restrictSize, nil); CGFloat textHeight = coreTextSize.height; CTFrameRef frame = [self createFrameWithFramesetter:framesetter config:config height:textHeight]; CoreTextData *data = [[CoreTextData alloc] init]; data.ctFrame = frame; data.height = textHeight; CFRelease(frame); CFRelease(framesetter); return data; } + (CTFrameRef)createFrameWithFramesetter:(CTFramesetterRef)framesetter config:(CTFrameParserConfig *)config height:(CGFloat)height { CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(0, 0, config.width, height)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); CFRelease(path); return frame; } @end
CoreTextData 類:
#import@interface CoreTextData : NSObject @property (assign, nonatomic) CTFrameRef ctFrame; @property (assign, nonatomic) CGFloat height; @end
#import "CoreTextData.h" @implementation CoreTextData - (void)setCtFrame:(CTFrameRef)ctFrame { if (_ctFrame != ctFrame) { if (_ctFrame != nil) { CFRelease(_ctFrame); } CFRetain(ctFrame); _ctFrame = ctFrame; } } - (void)dealloc { if (_ctFrame != nil) { CFRelease(_ctFrame); _ctFrame = nil; } } @end
CTDisplayView 類:
#import#import "CoreTextData.h" @interface CTDisplayView : UIView @property (strong, nonatomic) CoreTextData * data; @end
#import "CTDisplayView.h" @implementation CTDisplayView - (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetTextMatrix(context, CGAffineTransformIdentity); CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1.0, -1.0); if (self.data) { CTFrameDraw(self.data.ctFrame, context); } } @end
這四個類的邏輯與先前 Hello World 基本一致,只是拆分到不同類別中完成。此外,CTFrameParser 新增了取得繪製區域高度的方法,並把高度存入 CoreTextData。之所以要取得高度,是因為在許多實務場景中,我們得先知道內容高度才能進行繪製。
例如 UITableView 渲染時,會先向 delegate 回呼以下方法取得每個 cell 的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
接著 UITableView 會計算當前捲動位置需要哪些 cell,再對需要繪製的 cell 回呼以下方法取得實例:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
若我們用 CoreText 作為 TableViewCell 的內容,就必須在每個 cell 繪製前先知道所需高度,否則 UITableView 將無法正常運作。
完成這四個類後,就能在 ViewController.m 中加入以下程式碼,配置 CTDisplayView 的顯示內容、位置、高度、字型與顏色:
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet CTDisplayView *ctView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CTFrameParserConfig *config = [[CTFrameParserConfig alloc] init]; config.textColor = [UIColor redColor]; config.width = self.ctView.width; CoreTextData *data = [CTFrameParser parseContent:@" 按照以上原則,我們將 CTDisplayView 中的部分內容拆開。" config:config]; self.ctView.data = data; self.ctView.height = data.height; self.ctView.backgroundColor = [UIColor yellowColor]; } @end
注意:從 Xcode 4.0 起,預設的界面編輯已啟用 Use Autolayout。但由於我們在程式碼中直接修改了 ctView 的 frame,因此需在 Main_iPhone.storyboard 中取消勾選 Use Autolayout。

以下是本框架的 UML 示意圖。從圖中可看出,這四個 CoreText 類的關係是:CTFrameParser 透過 CTFrameParserConfig 產生 CoreTextData;CTDisplayView 透過持有 CoreTextData 取得繪製所需的全部資訊;ViewController 則配置 CTFrameParserConfig、取得 CoreTextData,最後賦值給 CTDisplayView,完成畫面顯示。

說明:整個工程位於 basic_arch 分支,讀者可用 git checkout basic_arch 切換查看。此外,專案中有一個名為 UIView+frameAdjust.m 的檔案,透過 Category 為 UIView 增加了直接設定 height 的方法。
前面的例子為 CTFrameParser 增加了把 NSString 轉為 CoreTextData 的方法,但這樣的實作有局限:內容雖能定制字型大小、顏色、行高,卻無法定制其中某一部分。例如想讓前三個字顯示紅色、其餘黑色,就辦不到。
解法很簡單:讓 CTFrameParser 支援接受 NSAttributedString 作為參數,再由 ViewController 設定我們想要的屬性資訊。
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CTFrameParserConfig *config = [[CTFrameParserConfig alloc] init]; config.width = self.ctView.width; config.textColor = [UIColor blackColor]; NSString *content = @" 對於上面的例子,我們給 CTFrameParser 增加了一個將 NSString 轉 " " 換為 CoreTextData 的方法。" " 但這樣的實現方式有很多局限性。"; NSDictionary *attr = [CTFrameParser attributesWithConfig:config]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:content attributes:attr]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 7)]; CoreTextData *data = [CTFrameParser parseAttributedContent:attributedString config:config]; self.ctView.data = data; self.ctView.height = data.height; self.ctView.backgroundColor = [UIColor yellowColor]; } @end
執行結果如下圖,我們很輕易就把前面七個字變成了紅色。

更進一步,實務中我們更希望透過一個排版檔案來設定文字內容、顏色、字型大小等資訊。我在開發產品時自訂了一套基於 UBB 的排版模板,但實作其解析器篇幅龐大,且並非本章重點,因此改用一個較簡單的排版檔案來講解其思想。
我們規定排版模板為 JSON 格式。JSON 是一種輕量級的資料交換格式,易於閱讀、編寫,也易於機器解析與產生。iOS 從 5.0 起提供了 NSJSONSerialization 類庫來方便解析 JSON;在 5.0 之前,業界則有 JSONKit 等開源庫可用。
我們的排版模板示例如下:
[ { "color" : "blue", "content" : " 更進一步地,實際工作中,我們更希望通過一個排版文件,來設置需要排版的文字的 ", "size" : 16, "type" : "txt" }, { "color" : "red", "content" : " 內容、顏色、字體 ", "size" : 22, "type" : "txt" }, { "color" : "black", "content" : " 大小等信息。\n", "size" : 16, "type" : "txt" }, { "color" : "default", "content" : " 我在開發猿題庫應用時,自己定義了一個基於 UBB 的排版模版。", "type" : "txt" } ]
透過 NSJSONSerialization,我們能把模板轉成 NSArray,每個元素是一個代表相同設定文字的 NSDictionary。為求簡單,設定檔只支援顏色與字級,但讀者可依相同思路輕易擴充其他設定。
接下來為 CTFrameParser 增加一個方法,讓它能從這種模板產生 CoreTextData。最終實作如下:
// 方法一 + (CoreTextData *)parseTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config { NSAttributedString *content = [self loadTemplateFile:path config:config]; return [self parseAttributedContent:content config:config]; } // 方法二 + (NSAttributedString *)loadTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config { NSData *data = [NSData dataWithContentsOfFile:path]; NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init]; if (data) { NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; if ([array isKindOfClass:[NSArray class]]) { for (NSDictionary *dict in array) { NSString *type = dict[@"type"]; if ([type isEqualToString:@"txt"]) { NSAttributedString *as = [self parseAttributedContentFromNSDictionary:dict config:config]; [result appendAttributedString:as]; } } } } return result; } // 方法三 + (NSAttributedString *)parseAttributedContentFromNSDictionary:(NSDictionary *)dict config:(CTFrameParserConfig*)config { NSMutableDictionary *attributes = [self attributesWithConfig:config]; UIColor *color = [self colorFromTemplate:dict[@"color"]]; if (color) { attributes[(id)kCTForegroundColorAttributeName] = (id)color.CGColor; } CGFloat fontSize = [dict[@"size"] floatValue]; if (fontSize > 0) { CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialMT", fontSize, NULL); attributes[(id)kCTFontAttributeName] = (__bridge id)fontRef; CFRelease(fontRef); } NSString *content = dict[@"content"]; return [[NSAttributedString alloc] initWithString:content attributes:attributes]; } // 方法四 + (UIColor *)colorFromTemplate:(NSString *)name { if ([name isEqualToString:@"blue"]) { return [UIColor blueColor]; } else if ([name isEqualToString:@"red"]) { return [UIColor redColor]; } else if ([name isEqualToString:@"black"]) { return [UIColor blackColor]; } else { return nil; } } // 方法五 + (CoreTextData *)parseAttributedContent:(NSAttributedString *)content config:(CTFrameParserConfig*)config { CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)content); CGSize restrictSize = CGSizeMake(config.width, CGFLOAT_MAX); CGSize coreTextSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,0), nil, restrictSize, nil); CGFloat textHeight = coreTextSize.height; CTFrameRef frame = [self createFrameWithFramesetter:framesetter config:config height:textHeight]; CoreTextData *data = [[CoreTextData alloc] init]; data.ctFrame = frame; data.height = textHeight; CFRelease(frame); CFRelease(framesetter); return data; } // 方法六 + (CTFrameRef)createFrameWithFramesetter:(CTFramesetterRef)framesetter config:(CTFrameParserConfig *)config height:(CGFloat)height { CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(0, 0, config.width, height)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); CFRelease(path); return frame; }
以上程式碼由六個子方法構成:方法一提供對外接口,呼叫方法二讀取 JSON 模板,再呼叫方法五產生 CoreTextData;方法二讀取 JSON 並呼叫方法三完成轉換;方法三把 NSDictionary 轉為 NSAttributedString;方法四提供 NSString 轉 UIColor 的功能;方法五把 NSAttributedString 與 config 轉成 CoreTextData;方法六則是方法五的輔助函式。
接著修改 ViewController 的呼叫,改為從模板檔案載入內容:
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CTFrameParserConfig *config = [[CTFrameParserConfig alloc] init]; config.width = self.ctView.width; NSString *path = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"json"]; CoreTextData *data = [CTFrameParser parseTemplateFile:path config:config]; self.ctView.data = data; self.ctView.height = data.height; self.ctView.backgroundColor = [UIColor whiteColor]; } @end
執行後的結果如下圖。可以看到,透過一個簡單的模板檔案,我們已經能很方便地定義排版設定。
