在 CoreText 中做全文搜尋並高亮結果是很普遍的需求。但實作時會撞上一個問題:CoreText 不支援 NSBackgroundColorAttributeName。
如果用 UILabel 搭配 NSAttributedString,一行就能搞定:
[attributedString addAttribute:NSBackgroundColorAttributeName
value:[UIColor orangeColor]
range:range];
_conLabel.attributedText = attributedString;
但同樣的屬性放到 CoreText 上,畫出來完全沒有背景色——CoreText 只負責字形的排版與繪製,背景方塊需要你自己畫。
思路是:遍歷 CTFrame 的每一行、每個 glyph run,凡是帶有自訂背景色屬性的 run,就用 CTRunGetTypographicBounds 取得寬度、CTRunGetPositionsPtr 取得起始座標,然後用 CGContext 畫一個矩形填進去。
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
// CoreText 的座標系與 UIKit 相反,需先做翻轉
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
NSArray *lines = (NSArray *)CTFrameGetLines((CTFrameRef)NCTFrame);
if (lines.count) {
CGPoint *lineOrigins = malloc(lines.count * sizeof(CGPoint));
CTFrameGetLineOrigins((CTFrameRef)NCTFrame,
CFRangeMake(0, lines.count),
lineOrigins);
int i = 0;
for (id aLine in lines) {
NSArray *glyphRuns = (NSArray *)CTLineGetGlyphRuns((CTLineRef)aLine);
CGFloat height = lineOrigins[i].y;
for (id run in glyphRuns) {
CFDictionaryRef dicRef = CTRunGetAttributes((CTRunRef)run);
NSDictionary *dic = (__bridge NSDictionary *)dicRef;
if ([dic objectForKey:@"NSBackgroundColor"] != nil && _isSearch == YES) {
UIColor *BGColor = [dic objectForKey:@"NSBackgroundColor"];
CGPoint *ary = (CGPoint *)CTRunGetPositionsPtr((CTRunRef)run);
float lineheight;
if (lines.count >= 2) {
lineheight = lineOrigins[lines.count - 2].y - lineOrigins[lines.count - 1].y;
} else {
lineheight = 28; // 只有一行時的 fallback
}
float runWidth = CTRunGetTypographicBounds((CTRunRef)run,
CFRangeMake(0, 0),
NULL, NULL, NULL);
CGRect rectangle = CGRectMake(ary[0].x, height - 8, runWidth, lineheight);
CGContextSetFillColorWithColor(context, BGColor.CGColor);
CGContextFillRect(context, rectangle);
// 若要邊框,改用下面三行
// CGContextSetStrokeColorWithColor(context, BGColor.CGColor);
// CGContextAddRect(context, rectangle);
// CGContextStrokePath(context);
}
}
i++;
}
free(lineOrigins); // 別忘了釋放 malloc 的記憶體
}
// 最後才把文字畫上去,否則會被背景蓋住
CTFrameDraw((CTFrameRef)NCTFrame, context);
}
1. 座標系翻轉。CoreText 使用左下為原點的座標系,與 UIKit 左上為原點相反。不做 TranslateCTM + ScaleCTM(1.0, -1.0),文字會上下顛倒。
2. 畫序:先背景,後文字。必須先把所有高亮矩形填完,最後再一次 CTFrameDraw,否則後畫的背景會蓋掉先畫的字。
3. 自訂屬性 key。NSBackgroundColor 不是 CoreText 的標準屬性,它會被原封不動保留在 CTRun 的 attributes 字典中——這正好可以拿來當作「這段要高亮」的標記。實作時建議自訂一個專屬的 key 常數,避免與其他 attribute 混淆。
4. malloc 一定要 free。原始碼中 lineOrigins 用 malloc 配置,在提前 return 的路徑上很容易漏掉,造成記憶體洩漏。
原文作者提到「取得行高時沒找到什麼好方法」,這個問題確實存在,但並非無解。上面用「相鄰兩行起點相減」的做法在行距均勻時可用,卻在只有一行或行距不一致時失效。
更可靠的方式有兩種:
方法一:用 CTRunGetTypographicBounds 的 ascent / descent 參數。
CGFloat ascent, descent, leading;
CGFloat width = CTRunGetTypographicBounds((CTRunRef)run, CFRangeMake(0, 0),
&ascent, &descent, &leading);
CGFloat runHeight = ascent + descent + leading;
這樣得到的是該 run 實際佔用的行高,比猜測相鄰行距準確得多,也能正確處理含中英混排、不同字型大小的段落。
方法二:改用 NSLayoutManager + NSTextContainer。自 iOS 7 起的 Text Kit 架構,能直接取得 boundingRectForGlyphRange:inTextContainer:,行高與背景繪製都有現成 API,程式碼量遠少於直接操作 CoreText。
方法三:改用 yyText / YYLabel 等成熟庫。這類庫已完整處理高亮、行高、行距、附件與點擊事件,除非有特殊的排版需求,否則重造輪子的成本遠高於收益。
CoreText 適合需要**完全自訂排版**的場景:多欄、豎排、圖文混排、自訂字距與基線。若只是要顯示一段帶樣式的文字,UILabel + NSAttributedString 或 Text Kit 就夠了——CoreText 的學習曲線與維護成本,值得留給真正需要它的時候。