NT_iOS笔记—CoreText添加文字背景色(搜索的高亮显示)

来源:互联网 发布:windows计划任务日志 编辑:程序博客网 时间:2024/05/22 13:56

转载请标明出处:http://blog.csdn.net/nt_tian/article/details/42458647

在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);                    CGFloat runAscent,runDescent;                    float RunWidth=CTRunGetTypographicBounds((CTRunRef)run, CFRangeMake(0,0), &runAscent, &runDescent, NULL);                    CGFloat runHeight = runAscent + (runDescent);                    CGRect rectangle = CGRectMake(ary[0].x, height-4.3, RunWidth, runHeight);                    CGContextSetFillColorWithColor(context,BGColor.CGColor);                    CGContextFillRect(context , rectangle);                                        //                    绘制矩形框                    //                    CGContextSetStrokeColorWithColor(context, [BGColor CGColor]);//边框色                    //                    CGContextAddRect(context, rectangle);                    //                    CGContextStrokePath(context);//绘制                                    }                ......            }            i++;        }                free(lineOrigins);    }}


6 1