NT_iOS筆記—CoreText添加文字背景色(搜尋的高亮顯示)
在CoreText裡進行全文檢索搜尋,搜尋的結果需要高亮顯示,這個已經是很普遍的做法了。
在搜尋結果列表中可以通過UILabel直接顯示
[attributedString addAttribute: NSBackgroundColorAttributeName value:[UIColor orangeColor] range:range];_conLabel.attributedText=attributedString;
但是當我開始進行CoreText文字高亮顯示的時候發現了一個問題,CoreText對NSMutableAttributedString 中的NSBackgroundColorAttributeName屬性不支援。
網上查了一下,CoreText的文字背景色需要自己手動的畫上去。
好吧,那就只能自己畫了,上代碼:
- (void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); 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 width =lineOrigins[i].x-lineOrigins[0].x; 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; } 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); }}
這裡還遇到了一個問題暫時沒有找到好的方法:在擷取行高的時候,沒有找到什麼好的方法。
如果誰知道可以告訴我,我也可以學習改進一下。