NT_iOS筆記—CoreText添加文字背景色(搜索的高亮顯示) – iPhone手機開發技術文章 iPhone軟體開發教學課程

 

在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);
    }
}

這裡還遇到瞭一個問題暫時沒有找到好的方法:在獲取行高的時候,沒有找到什麼好的方法。

 

如果誰知道可以告訴我,我也可以學習改進一下。
 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *