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
- NT_iOS笔记—CoreText添加文字背景色(搜索的高亮显示)
- 改变高亮显示的变量的背景色(默认暗灰色)在这里设置
- Android学习笔记(三) —— 更改TextView文字颜色及文字背景色
- 鼠标选取文字,添加背景色
- Eclipse设置相同变量背景色高亮显示
- Eclipse设置相同变量背景色高亮显示
- table中tr背景色高亮显示动态设置
- Eclipse设置相同变量背景色高亮显示
- Eclipse设置相同变量背景色高亮显示
- NT_iOS笔记—iOS图片显示3_界面的手动旋转(UIDeviceOrientation和UIInterfaceOrientation)
- NT_iOS笔记—iOS添加字体
- NT_iOS笔记—webview添加Cookie
- vs中改变 变量引用的 背景色 高亮显示
- markdown编辑器语法——文字颜色、大小、字体与背景色的设置(转)
- markdown编辑器语法——文字颜色、大小、字体与背景色的设置(全)
- 去掉桌面图标文字的背景色
- 不伤眼睛的文字背景色
- 不伤眼睛的文字背景色
- Weblogic安全性编程在 Java 客户端中使用 JAAS 身份验证
- 文件传送协议(FTP,TFTP,NFS)
- Android之Activity生命周期详解
- 黑马程序员——Java面向对象(this关键字、静态、单例设计模式、继承)
- js arguments对象
- NT_iOS笔记—CoreText添加文字背景色(搜索的高亮显示)
- Linux locale命令
- 仿亚马逊左侧导航(精心设计的人机交互)
- android主线程访问网络出错
- 中缀式转换为后缀式(逆波兰式)方法
- jsp <c:if>判断List是否为空
- 禁止晚上吃姜
- iOS UIWebView 无法确定web页面的真实高度
- NPAPI——实现非IE浏览器的类似ActiveX的本地程序(插件)调用