在CoreText裡進行全文搜索,搜索的結果需要高亮顯示,這個已經是很普遍的做法了。
在搜索結果列表中可以通過UILabel直接顯示
[attributedString addAttribute: NSBackgroundColorAttributeName value:[UIColor orangeColor] range:range]; _conLabel.attributedText=attributedString;但是當我開始進行CoreText文字高亮顯示的時候發現了一個問題,CoreText對NSMutableAttributedString 中的NSBackgroundColorAttributeName屬性不支持。
好吧,那就只能自己畫了,上代碼:
- (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);
}
}
如果誰知道可以告訴我,我也可以學習改進一下。