boundingRectWithSize 的使用, 计算UILable高度, 包含Emoji及多属性string.
2016-04-27 17:02
465 查看
iOS的文字高度计算一直是个问题, 苹果也一直在改, 这几天看了一下 boundingRectWithSize 方法.
踩了几个坑后, 总算找到比较好的使用方法.
参考: http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size 使用时的注意事项:
1: NSAttributedString 的每个部分都要至少设置两个属性:
NSFontAttributeName
NSForegroundColorAttributeName
2: NSStringDrawingOptions 的值, 在多行的情况下, 至少要有
NSStringDrawingUsesLineFragmentOrigin
NSStringDrawingUsesFontLeading
3: 如果文字中可能会出现emoji表情的话, emoji的高度比文字要高一点点,
我的方便是简单的在高度基础上加了两个像素.
(用CoreText可能会好一些, 但相对复杂.)
附代码:
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
踩了几个坑后, 总算找到比较好的使用方法.
参考: http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size 使用时的注意事项:
1: NSAttributedString 的每个部分都要至少设置两个属性:
NSFontAttributeName
NSForegroundColorAttributeName
2: NSStringDrawingOptions 的值, 在多行的情况下, 至少要有
NSStringDrawingUsesLineFragmentOrigin
NSStringDrawingUsesFontLeading
3: 如果文字中可能会出现emoji表情的话, emoji的高度比文字要高一点点,
我的方便是简单的在高度基础上加了两个像素.
(用CoreText可能会好一些, 但相对复杂.)
附代码:
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:fullDescAndTagStr]; NSRange allRange = [fullDescAndTagStr rangeOfString:fullDescAndTagStr]; [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:allRange]; [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:allRange]; NSRange destRange = [fullDescAndTagStr rangeOfString:tagStr]; [attrStr addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x009cdd) range:destRange]; CGFloat titleHeight; NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading; CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX) options:options context:nil]; titleHeight = ceilf(rect.size.height); return titleHeight+2; // 加两个像素,防止emoji被切掉.
相关文章推荐
- git Pull Request 是什么意思?
- Tiled GPU perf. warning: Backbuffer was not cleared/discarded, doing Render.OpaqueGeometry/RenderFor
- Java常见错误-“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- 【小米3使用经验】小米3联通版 miui7.2.11稳定版刷机
- UIView-iOS初学
- ueditor子表控件绑定事件的扩展优化
- Android酷炫实用的开源框架(UI框架)
- Build.gradle详细配置说明
- 在继承自 UITableViewController 重构时使用 xib 无法显示问题,
- autolayout中 top layout guide详解
- 检查request返回值类型的一个小方法
- Woobuntu woobuntu_build.sh hacking
- 【iOS】UILabel自适应高度和自动换行
- qemu的virtqueue实现
- POJ 3061 Subsequence (二分查找)
- GeoQuiz 第二章挑战练习代码
- CharSequence与String以及stringbuffer与stringbuilder--Android学习笔记6-2
- 关于easyui-combobox在表单提交的时候如何做非空校验(笔记)
- UIButton中setTitleEdgeInsets和setImageEdgeInsets的使用
- hibernate sqlQuery mysql别名问题