Reprint please indicate source: http://blog.csdn.net/nt_tian/article/details/42458647
In Coretext full-text search, the results of the search need to be highlighted, this is a very common practice.
The search results list can be directly displayed by Uilabel
[Attributedstring addattribute:nsbackgroundcolorattributename value:[uicolor Orangecolor] Range:range];_ conlabel.attributedtext=attributedstring;
But when I started coretext text highlighting, I found a problem, Coretextnsmutableattributedstring in theThe Nsbackgroundcolorattributename property is not supported.
online Check, coretext text background color need to manually draw up.
Well, then you can only draw it yourself, on the code:
-(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:@" Nsbackgroundcolo R "]; Cgpoint *ary= (Cgpoint *) ctrungetpositionsptr ((ctrunref) run); float lineheight; if (lines.count>=2) {Lineheight=lineorigins[lines.count-2].y-lineorigins[lin ES.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); Draw Rectangle//Cgcontextsetstrokecolorwithcolor (context, [BGColor cgcolor]);//Border color//cgcontextaddrect (context, rectangle);//Cgcontextstrokepath (context);//Draw } ...... } i++; } free (lineorigins); }}
There's also a problem here. There is no good way to find it at the moment: there is no good way to get a high line.
If anyone knows can tell me, I can also learn to improve.
Nt_ios Notes-coretext Add text background color (search highlighting)