在上一篇《基於 CoreText 的排版引擎:基礎》中,我們掌握了排版的基本知識。本篇将进一步增加難度,讓排版引擎支援圖片與文字混排,並能處理圖片、連結的點擊互動。
首先來讓排版引擎具備處理圖片的能力。在設定模板檔案時,我們早已保留了一個名為 type 的欄位,用來標示內容類型。先前 type 的值都是 txt,這次我們新增一個值為 img 的類型來代表圖片。
把上一節的 content.json 修改如下,其中加入了兩個 type 為 img 的設定項。由於是圖片,顏色、字級等不適用,因此改為額外提供三個圖片專屬屬性:
一個名為 width 的屬性,用來設定圖片顯示的寬度;一個名為 height 的屬性,用來設定圖片顯示的高度;還有一個名為 name 的屬性,用來設定圖片的資源名稱。
[ { "type" : "img", "width" : 200, "height" : 108, "name" : "coretext-image-1.jpg" }, { "color" : "blue", "content" : " 更進一步地,實際工作中,我們更希望通過一個排版文件,來設置需要排版的文字的 ", "size" : 16, "type" : "txt" }, { "color" : "red", "content" : " 內容、顏色、字體 ", "size" : 22, "type" : "txt" }, { "color" : "black", "content" : " 大小等信息。\n", "size" : 16, "type" : "txt" }, { "type" : "img", "width" : 200, "height" : 130, "name" : "coretext-image-2.jpg" }, { "color" : "default", "content" : " 我在開發猿題庫應用時,自己定義了一個基於 UBB 的排版模版,但是實現該排版文件的解析器要花費大量的篇幅,考慮到這並不是本章的重點,所以我們以一個較簡單的排版文件來講解其思想。", "type" : "txt" } ]
你可能會問:圖片本身就帶有寬高資訊,為何還要在模板裡指定?原因在於,真實開發中模板與圖片通常都從伺服器取得,模板是純文字,下載速度快;圖片則下載慢,而且為了省流量,往往要等到真正需要顯示時才載入。
如果不把圖片寬高寫進模板,CoreText 在排版時就無法得知繪製所需的高度,也就無法設定 CoreTextData 類中的 height 資訊。缺少高度資訊,會對 UITableView 一類控件的排版造成影響。因此,除非你能保證圖片在繪製前一定都在本地,否則就應該提前提供圖片的寬高。
完成模板修改後,挑選兩張測試圖片,分別命名為 coretext-image-1.jpg 與 coretext-image-2.jpg(與模板中的值一致),再把它們拖進專案。向 Xcode 加入圖片資源屬於基礎操作,這裡不再贅述。
接著要改造的是 CTFrameParser 類,讓解析模板的方法能處理 type 為 img 的設定。
動手前,先了解 CTFrame 的內部結構。我們先用 NSAttributeString 與設定資訊建立 CTFrameSetter,再由它產生 CTFrame。
在 CTFrame 內部,是由多個 CTLine 組成,每個 CTLine 代表一行;每個 CTLine 又由多個 CTRun 組成,每個 CTRun 代表一組風格一致的文字。我們無需手動管理 CTLine 與 CTRun 的建立過程。
下圖是 CTLine 與 CTRun 的示意圖。可以看到,第三行的 CTLine 由兩個 CTRun 構成:第一個是紅色大字的左半部,第二個則是右半部字體較小的文字。

雖然不必管理 CTRun 的建立,但我們可以透過設定某個 CTRun 的 CTRunDelegate,來指定這段文字在繪製時的高度、寬度與對齊方式等資訊。
說到底,CoreText 並不直接支援圖片排版。但我們可以在原本要顯示文字的位置放上一個特殊的空白字元,再把該字元的 CTRunDelegate 設為圖片的寬高,如此一來,最終產生的 CTFrame 便會在繪製時預留出圖片的位置。
由於 CTDisplayView 的繪製程式碼寫在 drawRect 中,我們可以直接用 CGContextDrawImage 把圖片畫上去。
理解原理後,就能開始動手。需要完成的工作包括:
改造 CTFrameParser 的 parseTemplateFile:config: 方法,使其支援解析 type 為 img 的節點,並為該節點設定 CTRunDelegate,讓繪製時能預留空白位置。改造 CoreTextData 類,加入圖片相關資訊與計算繪製區域的邏輯。改造 CTDisplayView 類,加入繪製圖片的邏輯。
先看 CTFrameParser 的改造。我們為 parseTemplateFile 增加一個名為 imageArray 的參數,用來保存解析時的圖片資訊。
+ (CoreTextData *)parseTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config { NSMutableArray *imageArray = [NSMutableArray array]; NSAttributedString *content = [self loadTemplateFile:path config:config imageArray:imageArray]; CoreTextData *data = [self parseAttributedContent:content config:config]; data.imageArray = imageArray; return data; }
接著修改 loadTemplateFile 方法,加入對 type 為 img 節點的處理。這段邏輯主要做兩件事:把當前圖片節點資訊存入 imageArray,以及建立一個空白占位符。
+ (NSAttributedString *)loadTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config imageArray:(NSMutableArray *)imageArray { 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]; } else if ([type isEqualToString:@"img"]) { CoreTextImageData *imageData = [[CoreTextImageData alloc] init]; imageData.name = dict[@"name"]; imageData.position = [result length]; [imageArray addObject:imageData]; NSAttributedString *as = [self parseImageDataFromNSDictionary:dict config:config]; [result appendAttributedString:as]; } } } } return result; }
最後建立一個最關鍵的方法 parseImageDataFromNSDictionary,用來生成圖片空白占位符並設定其 CTRunDelegate。
static CGFloat ascentCallback(void *ref){ return [(NSNumber*)[(__bridge NSDictionary*)ref objectForKey:@"height"] floatValue]; } static CGFloat descentCallback(void *ref){ return 0; } static CGFloat widthCallback(void* ref){ return [(NSNumber*)[(__bridge NSDictionary*)ref objectForKey:@"width"] floatValue]; } + (NSAttributedString *)parseImageDataFromNSDictionary:(NSDictionary *)dict config:(CTFrameParserConfig*)config { CTRunDelegateCallbacks callbacks; memset(&callbacks, 0, sizeof(CTRunDelegateCallbacks)); callbacks.version = kCTRunDelegateVersion1; callbacks.getAscent = ascentCallback; callbacks.getDescent = descentCallback; callbacks.getWidth = widthCallback; CTRunDelegateRef delegate = CTRunDelegateCreate(&callbacks, (__bridge void *)(dict)); unichar objectReplacementChar = 0xFFFC; NSString * content = [NSString stringWithCharacters:&objectReplacementChar length:1]; NSDictionary * attributes = [self attributesWithConfig:config]; NSMutableAttributedString * space = [[NSMutableAttributedString alloc] initWithString:content attributes:attributes]; CFAttributedStringSetAttribute((CFMutableAttributedStringRef)space, CFRangeMake(0, 1), kCTRunDelegateAttributeName, delegate); CFRelease(delegate); return space; }
接著改造 CoreTextData,新增 imageArray 成員,用來保存繪製圖片所需的資訊。
#import#import "CoreTextImageData.h" @interface CoreTextData : NSObject @property (assign, nonatomic) CTFrameRef ctFrame; @property (assign, nonatomic) CGFloat height; @property (strong, nonatomic) NSArray * imageArray; @end
在設定 imageArray 時,還會呼叫一個新建立的 fillImagePosition 方法,用來找出每張圖片繪製時的實際位置。
- (void)setImageArray:(NSArray *)imageArray { _imageArray = imageArray; [self fillImagePosition]; } - (void)fillImagePosition { if (self.imageArray.count == 0) { return; } NSArray *lines = (NSArray *)CTFrameGetLines(self.ctFrame); int lineCount = [lines count]; CGPoint lineOrigins[lineCount]; CTFrameGetLineOrigins(self.ctFrame, CFRangeMake(0, 0), lineOrigins); int imgIndex = 0; CoreTextImageData * imageData = self.imageArray[0]; for (int i = 0; i < lineCount; ++i) { if (imageData == nil) { break; } CTLineRef line = (__bridge CTLineRef)lines[i]; NSArray * runObjArray = (NSArray *)CTLineGetGlyphRuns(line); for (id runObj in runObjArray) { CTRunRef run = (__bridge CTRunRef)runObj; NSDictionary *runAttributes = (NSDictionary *)CTRunGetAttributes(run); CTRunDelegateRef delegate = (__bridge CTRunDelegateRef)[runAttributes valueForKey:(id)kCTRunDelegateAttributeName]; if (delegate == nil) { continue; } NSDictionary * metaDic = CTRunDelegateGetRefCon(delegate); if (![metaDic isKindOfClass:[NSDictionary class]]) { continue; } CGRect runBounds; CGFloat ascent; CGFloat descent; runBounds.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL); runBounds.size.height = ascent + descent; CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL); runBounds.origin.x = lineOrigins[i].x + xOffset; runBounds.origin.y = lineOrigins[i].y; runBounds.origin.y -= descent; CGPathRef pathRef = CTFrameGetPath(self.ctFrame); CGRect colRect = CGPathGetBoundingBox(pathRef); CGRect delegateBounds = CGRectOffset(runBounds, colRect.origin.x, colRect.origin.y); imageData.imagePosition = delegateBounds; imgIndex++; if (imgIndex == self.imageArray.count) { imageData = nil; break; } else { imageData = self.imageArray[imgIndex]; } } } }
要支援圖片點擊,需為 CTDisplayView 加入使用者點擊偵測,判斷點擊位置是否落在圖片上,若是則觸發相應邏輯。蘋果提供的 UITapGestureRecognizer 正好勝任,於是採用它來偵測點擊。
這裡先示範點擊圖片後用 NSLog 印出一行日誌,實際應用中讀者可依業務需求自行調整。
先為 CTDisplayView 加上 UITapGestureRecognizer:
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self setupEvents]; } return self; } - (void)setupEvents { UIGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapGestureDetected:)]; tapRecognizer.delegate = self; [self addGestureRecognizer:tapRecognizer]; self.userInteractionEnabled = YES; }
再來加上手勢回呼函式:
- (void)userTapGestureDetected:(UIGestureRecognizer *)recognizer { CGPoint point = [recognizer locationInView:self]; for (CoreTextImageData * imageData in self.data.imageArray) { CGRect imageRect = imageData.imagePosition; CGPoint imagePosition = imageRect.origin; imagePosition.y = self.bounds.size.height - imageRect.origin.y - imageRect.size.height; CGRect rect = CGRectMake(imagePosition.x, imagePosition.y, imageRect.size.width, imageRect.size.height); if (CGRectContainsPoint(rect, point)) { NSLog(@"bingo"); break; } } }
在檢視層級中,CTDisplayView 往往嵌在多層 UIView 之下,可能是最外層 View Controller 的 View 的「孩子的孩子」。這種多層結構下,很難用 delegate 把點擊事件一層層往外傳,因此改用 NSNotification 來處理會更合適。

在 Demo 中,我們在最外層的 View Controller 監聽圖片點擊通知,收到後便進入新畫面顯示點擊內容。
註:讀者可將 demo 切換到 image_click 分支查看範例程式碼。
修改模板,新增一個名為 link 的類型來表示連結內容:
[ { "color" : "default", "content" : " 這在這裡嘗試放一個參考鏈接:", "type" : "txt" }, { "color" : "blue", "content" : " 鏈接文字 ", "url" : "https://blog.devtang.com", "type" : "link" }, { "color" : "default", "content" : " 大家可以嘗試點擊一下 ", "type" : "txt" } ]
先新增一個 CoreTextLinkData 類,用來記錄解析 JSON 時的連結資訊:
@interface CoreTextLinkData : NSObject @property (strong, nonatomic) NSString * title; @property (strong, nonatomic) NSString * url; @property (assign, nonatomic) NSRange range; @end
接著修改 CTFrameParser,加入解析連結的邏輯:
+ (NSAttributedString *)loadTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config imageArray:(NSMutableArray *)imageArray linkArray:(NSMutableArray *)linkArray { 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"]) { } else if ([type isEqualToString:@"img"]) { } else if ([type isEqualToString:@"link"]) { NSUInteger startPos = result.length; NSAttributedString *as = [self parseAttributedContentFromNSDictionary:dict config:config]; [result appendAttributedString:as]; NSUInteger length = result.length - startPos; NSRange linkRange = NSMakeRange(startPos, length); CoreTextLinkData *linkData = [[CoreTextLinkData alloc] init]; linkData.title = dict[@"content"]; linkData.url = dict[@"url"]; linkData.range = linkRange; [linkArray addObject:linkData]; } } } } return result; }
然後新增一個 Utils 類,專門處理「點擊是否落在連結上」的判斷。關鍵是透過 CTLineGetStringIndexForPosition 取得點擊位置對應到字串上的索引,進而判斷該字元是否屬於某個連結。
+ (CoreTextLinkData *)touchLinkInView:(UIView *)view atPoint:(CGPoint)point data:(CoreTextData *)data { CTFrameRef textFrame = data.ctFrame; CFArrayRef lines = CTFrameGetLines(textFrame); if (!lines) return nil; CFIndex count = CFArrayGetCount(lines); CoreTextLinkData *foundLink = nil; CGPoint origins[count]; CTFrameGetLineOrigins(textFrame, CFRangeMake(0,0), origins); CGAffineTransform transform = CGAffineTransformMakeTranslation(0, view.bounds.size.height); transform = CGAffineTransformScale(transform, 1.f, -1.f); for (int i = 0; i < count; i++) { CGPoint linePoint = origins[i]; CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect flippedRect = [self getLineBounds:line point:linePoint]; CGRect rect = CGRectApplyAffineTransform(flippedRect, transform); if (CGRectContainsPoint(rect, point)) { CGPoint relativePoint = CGPointMake(point.x-CGRectGetMinX(rect), point.y-CGRectGetMinY(rect)); CFIndex idx = CTLineGetStringIndexForPosition(line, relativePoint); foundLink = [self linkAtIndex:idx linkArray:data.linkArray]; return foundLink; } } return nil; } + (CGRect)getLineBounds:(CTLineRef)line point:(CGPoint)point { CGFloat ascent = 0.0f; CGFloat descent = 0.0f; CGFloat leading = 0.0f; CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading); CGFloat height = ascent + descent; return CGRectMake(point.x, point.y - descent, width, height); } + (CoreTextLinkData *)linkAtIndex:(CFIndex)i linkArray:(NSArray *)linkArray { CoreTextLinkData *link = nil; for (CoreTextLinkData *data in linkArray) { if (NSLocationInRange(i, data.range)) { link = data; break; } } return link; }
最後改造 CTDisplayView,讓它在偵測到點擊後呼叫上述工具方法。這裡先示範點擊連結後印出日誌,實際應用中可自行調整效果。
- (void)userTapGestureDetected:(UIGestureRecognizer *)recognizer { CGPoint point = [recognizer locationInView:self]; CoreTextLinkData *linkData = [CoreTextUtils touchLinkInView:self atPoint:point data:self.data]; if (linkData) { NSLog(@"hint link!"); return; } }
註:Demo 中已實作點擊連結後跳轉新畫面、並以 UIWebView 顯示連結內容的邏輯,讀者可切換到 link_click 分支查看。
Demo 的 Gif 效果如下,讀者可用 git checkout image_support 切換到本章節狀態查看相關程式碼。
