ios NSAttributedString 具体解释
ios NSAttributedString 具体解释
NSAttributedString能够让我们使一个字符串显示的多样化,可是眼下到iOS 5为止,好像对它支持的不是非常好,由于显示起来不太方便(至少没有在OS X上方便)。
首先导入CoreText.framework,并在须要使用的文件里导入:
#import<CoreText/CoreText.h>
创建一个NSMutableAttributedString:
- NSMutableAttributedString *attriString = [[[NSMutableAttributedString alloc] initWithString:@"this is test!"]
- autorelease];
很常规的创建方式,接下来我们给它配置属性:
- //把this的字体颜色变为红色
- [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName
- value:(id)[UIColor redColor].CGColor
- range:NSMakeRange(0, 4)];
- //把is变为黄色
- [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName
- value:(id)[UIColor yellowColor].CGColor
- range:NSMakeRange(5, 2)];
- //改变this的字体,value必须是一个CTFontRef
- [attriString addAttribute:(NSString *)kCTFontAttributeName
- value:(id)CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName,
- 14,
- NULL)
- range:NSMakeRange(0, 4)];
- //给this加上下划线,value能够在指定的枚举中选择
- [attriString addAttribute:(NSString *)kCTUnderlineStyleAttributeName
- value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble]
- range:NSMakeRange(0, 4)];
- return attriString;
这样就算是配置好了,可是我们能够发现NSAttributedString继承于NSObject,而且不支持不论什么draw的方法,那我们就仅仅能自己draw了。写一个UIView的子类(如果命名为TView),在initWithFrame中把背景色设为透明(self.backgroundColor = [UIColor clearColor]),然后在重写drawRect方法:
- -(void)drawRect:(CGRect)rect{
- [super drawRect:rect];
- NSAttributedString *attriString = getAttributedString();
- CGContextRef ctx = UIGraphicsGetCurrentContext();
- CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));
- CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddRect(path, NULL, rect);
- CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
- CFRelease(path);
- CFRelease(framesetter);
- CTFrameDraw(frame, ctx);
- CFRelease(frame);
- }
在代码中我们调整了CTM(current transformation matrix),这是由于Quartz 2D的坐标系统不同,比方(10, 10)到(20, 20)的直线坐标:
坐标类似于数学中的坐标,能够先不调整CTM,看它是什么样子的,以下两种调整方法是全然一样的:
- CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));
==
- CGContextTranslateCTM(ctx, 0, rect.size.height);
- CGContextScaleCTM(ctx, 1, -1);
CTFramesetter是CTFrame的创建工厂,NSAttributedString须要通过CTFrame绘制到界面上,得到CTFramesetter后,创建path(绘制路径),然后得到CTFrame,最后通过CTFrameDraw方法绘制到界面上。
假设想要计算NSAttributedString所要的size,就须要用到这个API:
CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行时会算不准的,由于在CoreText里,行间距也是你来控制的。
设置行间距和换行模式都是设置一个属性:kCTParagraphStyleAttributeName,这个属性里面又分为非常多子
属性,当中就包含
- kCTLineBreakByCharWrapping
- kCTParagraphStyleSpecifierLineSpacingAdjustment
- //段落
- //line break
- CTParagraphStyleSetting lineBreakMode;
- CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //换行模式
- lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
- lineBreakMode.value = &lineBreak;
- lineBreakMode.valueSize = sizeof(CTLineBreakMode);
- //行间距
- CTParagraphStyleSetting LineSpacing;
- CGFloat spacing = 4.0; //指定间距
- LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
- LineSpacing.value = &spacing;
- LineSpacing.valueSize = sizeof(CGFloat);
- CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing};
- CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2); //第二个參数为settings的长度
- [attributedString addAttribute:(NSString *)kCTParagraphStyleAttributeName
- value:(id)paragraphStyle
- range:NSMakeRange(0, attributedString.length)];
-----------------------------------------猥琐的分界线-----------------------------------------
这并非唯一的方法,还有还有一种替代方案:
- CATextLayer *textLayer = [CATextLayer layer];
- textLayer.string = getAttributedString();
- textLayer.frame = CGRectMake(0, CGRectGetMaxY(view.frame), 200, 200);
- [self.view.layer addSublayer:textLayer];
CATextLayer能够直接支持NSAttributedString!
-----------------------------------------猥琐的分界线-----------------------------------------
效果图:
源代码地址

原文中确有描写叙述不适当的地方,比方:The upper-left corner of the context is (0, 0) 。实际上Quartz2D的坐标系统确实在左下角,仅仅是有一些技术在设置它们的graphics
context时使用了不同于Quartz的默认坐标系统。相对于Quartz来说,这些坐标系统是改动的坐标系统(modified coordinate system)。
UPDATED
在iOS6之后,创建一个AttributedString变成了一件轻松的事情,<CoreText/CoreText.h>已经不须要导入了。假设我要设置字体的颜色,能够直接这样:
- [textAttr addAttribute:NSForegroundColorAttributeName
- value:[UIColor redColor]
- range:NSMakeRange(0, text.length)];
ios NSAttributedString 具体解释的更多相关文章
- iOS SDK具体解释之NSCopying协议
原创blog,转载请注明出处 http://blog.csdn.net/hello_hwc?viewmode=contents 欢迎关注我的iOS SDK具体解释专栏 http://blog.csdn ...
- iOS SDK具体解释之UIDevice(系统版本号,设备型号...)
原创Blog,转载请注明出处 blog.csdn.net/hello_hwc 欢迎关注我的iOS SDK具体解释专栏 blog.csdn.net/column/details/huangwenchen ...
- iOS Animation具体解释
iOS Animation具体解释 本篇仅仅要解说iOS中动画的使用. Animtion主要分为两类:UIView动画和CoreAnimation动画. UIView动画有UIView属性动画,UIV ...
- iOS --NSAttributedString
字符属性可以应用于 attributed string 的文本中. 文/iOS_成才录(简书作者) 原文链接:http://www.jianshu.com/p/03a741246737 著作权归作者所 ...
- iOS 严重问题解释(crash)
问题1:Exception Type: 00000020 Exception Codes: 0x000000008badf00d Exception Note: SIMULATED (this is ...
- iOS常识名词解释 2016/04/05
Bundle : http://www.cnblogs.com/BigPolarBear/archive/2012/03/28/2421802.html http://blog.sina.com.cn ...
- 【精】iOS GCD 具体解释
一.介绍 1.什么是GCD? Grand Central Dispatch.是苹果公司开发的一套多核编程的底层API. GCD首次公布在Mac OS X 10.6,iOS4及以上也可用.GCD存在于l ...
- 关于IOS框架的解释
- iOS Core Animation具体解释(四)AutoLayout中的动画
原创blog.转载请注明出处 blog.csdn.net/hello_hwc 欢迎关注我的iOS SDK具体解释专栏 http://blog.csdn.net/column/details/huang ...
随机推荐
- PHP获得网页源码
获取网页源代码: <?php $lines = file('http://www.hoverreader.com/'); foreach ($lines as $line_num => $ ...
- Python 日期与时间
Python 3.6.4 import time, calendar, datetime print("距离1970年的秒数为:", time.time()) print(&quo ...
- matlab中函数学习——11月14日
1.记录数组元素个数函数:numel() 解释:number of array 相当于 prod(size(A)) 2.添加路径: addpath('.\3rdparty\ksvd'); 3.pada ...
- ASP.NET(二):Application、Session和Server对象
导读:在上篇博客中,总结了:Reques对象和Response对象的区别,以及IsPostBack属性的用法.其中说明Asp.net有6大对象,那么,这次就介绍剩下的3个对象,分别是:Applicat ...
- 九度oj 题目1160:放苹果
题目描述: 把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法. 输入: 第一行是测试数据的数目t(0 <= t ...
- 【强连通分量缩点】poj 1236 Network of Schools
poj.org/problem?id=1236 [题意] 给定一个有向图,求: (1)至少要选几个顶点,才能做到从这些顶点出发,可以到达全部顶点 (2)至少要加多少条边,才能使得从任何一个顶点出发,都 ...
- HashMap构造函数有哪些
hashMap有4个构造函数: public HashMap(int initialCapacity, float loadFactor) public HashMap(int initialCapa ...
- Spring JdbcTemplate 查询方法中的RowMapper实现汇总
实现一.在内部建立内联类实现RowMapper接口 package hysteria.contact.dao.impl; import java.sql.ResultSet; import java. ...
- hdu 1166 树状数组(线段树)
敌兵布阵 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submis ...
- HDU 5015 233 Matrix(网络赛1009) 矩阵快速幂
先贴四份矩阵快速幂的模板:http://www.cnblogs.com/shangyu/p/3620803.html http://www.cppblog.com/acronix/archive/20 ...