NT_iOS note-add text background color (search highlight) in CoreText)
Full-text search in CoreText requires that the search results be highlighted. This is a common practice.
You can use UILabel to directly display the search results in the search result list.
[attributedString addAttribute: NSBackgroundColorAttributeName value:[UIColor orangeColor] range:range];_conLabel.attributedText=attributedString;
However, when I started to highlight CoreText, I found a problem. CoreText does not support the NSBackgroundColorAttributeName attribute in NSMutableAttributedString.
After checking on the Internet, the text background color of CoreText needs to be manually painted.
Well, you can only draw it by yourself. The Code is as follows:
-(Void) drawRect :( CGRect) rect {CGContextRef context = UIGraphicsGetCurrentContext (); CGContextSetTextMatrix (context, callback); 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); CTFrameGet LineOrigins (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 *) dic Ref; 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 ); CGRect rectangle = CGRectMake (ary [0]. x, height-8, RunWidth, lineheight); CGContextSetFillColorWithColor (context, BGColor. CGColor); CGContextFillRect (context, rectangle); // draw a Rectangular Box // CGContextSetStrokeColorWithColor (context, [BGColor CGColor]); // border color // CGContextAddRect (context, rectangle ); // CGContextStrokePath (context); // draw }......} I ++;} free (lineOrigins );}}
There is also a problem that we have not found a good method for the moment: When the row is high, we have not found any good method.
If anyone knows, let me know. I can also learn how to improve it.