NSAttributedString 详解

来源:互联网 发布:java随机数生成1到100 编辑:程序博客网 时间:2024/05/08 03:06

转自:http://www.cnblogs.com/zhw511006/archive/2012/09/21/2696700.html


首先导入CoreText.framework,并在需要使用的文件中导入:

#import<CoreText/CoreText.h>

创建一个NSMutableAttributedString:

  1. NSMutableAttributedString *attriString = [[[NSMutableAttributedString alloc] initWithString:@"this is test!"]   
  2.                                               autorelease];  

非常常规的创建方式,接下来我们给它配置属性:

  1. //把this的字体颜色变为红色  
  2. [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  3.                     value:(id)[UIColor redColor].CGColor   
  4.                     range:NSMakeRange(0, 4)];  
  5. //把is变为黄色  
  6. [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  7.                     value:(id)[UIColor yellowColor].CGColor   
  8.                     range:NSMakeRange(5, 2)];  
  9. //改变this的字体,value必须是一个CTFontRef  
  10. [attriString addAttribute:(NSString *)kCTFontAttributeName  
  11.                     value:(id)CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName,  
  12.                                                    14,   
  13.                                                    NULL)  
  14.                     range:NSMakeRange(0, 4)];  
  15. //给this加上下划线,value可以在指定的枚举中选择  
  16. [attriString addAttribute:(NSString *)kCTUnderlineStyleAttributeName  
  17.                     value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble]  
  18.                     range:NSMakeRange(0, 4)];  
  19. return attriString;  

这样就算是配置好了,但是我们可以发现NSAttributedString继承于NSObject,并且不支持任何draw的方法,那我们就只能自己draw了。写一个UIView的子类(假设命名为TView),在initWithFrame中把背景色设为透明(self.backgroundColor = [UIColor clearColor]),然后在重写drawRect方法:

  1. -(void)drawRect:(CGRect)rect{  
  2.     [super drawRect:rect];  
  3.       
  4.     NSAttributedString *attriString = getAttributedString();  
  5.       
  6.     CGContextRef ctx = UIGraphicsGetCurrentContext();  
  7.     CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));  
  8.       
  9.     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);  
  10.     CGMutablePathRef path = CGPathCreateMutable();  
  11.     CGPathAddRect(path, NULL, rect);  
  12.       
  13.     CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);  
  14.     CFRelease(path);  
  15.     CFRelease(framesetter);  
  16.       
  17.     CTFrameDraw(frame, ctx);  
  18.     CFRelease(frame);  
  19. }  

在代码中我们调整了CTM(current transformation matrix),这是因为Quartz 2D的坐标系统不同,比如(10, 10)到(20, 20)的直线坐标:

 

坐标类似于数学中的坐标,可以先不调整CTM,看它是什么样子的,下面两种调整方法是完全一样的:

  1. CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));  

==

  1. CGContextTranslateCTM(ctx, 0, rect.size.height);  
  2. CGContextScaleCTM(ctx, 1, -1);  

CTFramesetter是CTFrame的创建工厂,NSAttributedString需要通过CTFrame绘制到界面上,得到CTFramesetter后,创建path(绘制路径),然后得到CTFrame,最后通过CTFrameDraw方法绘制到界面上

如果想要计算NSAttributedString所要的size,就需要用到这个API:

CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行时会算不准的,因为在CoreText里,行间距也是你来控制的。

设置行间距和换行模式都是设置一个属性:kCTParagraphStyleAttributeName,这个属性里面又分为很多子

属性,其中就包括

  • kCTLineBreakByCharWrapping
  • kCTParagraphStyleSpecifierLineSpacingAdjustment
设置如下:
  1. //段落  
  2.     //line break  
  3. CTParagraphStyleSetting lineBreakMode;  
  4. CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //换行模式  
  5. lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;  
  6. lineBreakMode.value = &lineBreak;  
  7. lineBreakMode.valueSize = sizeof(CTLineBreakMode);  
  8.     //行间距  
  9. CTParagraphStyleSetting LineSpacing;  
  10. CGFloat spacing = 4.0;  //指定间距  
  11. LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;  
  12. LineSpacing.value = &spacing;  
  13. LineSpacing.valueSize = sizeof(CGFloat);  
  14.   
  15. CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing};  
  16. CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2);   //第二个参数为settings的长度  
  17. [attributedString addAttribute:(NSString *)kCTParagraphStyleAttributeName  
  18.                          value:(id)paragraphStyle  
  19.                          range:NSMakeRange(0, attributedString.length)];  

-----------------------------------------猥琐的分界线-----------------------------------------

这并不是唯一的方法,还有另一种替代方案:

  1. CATextLayer *textLayer = [CATextLayer layer];  
  2. textLayer.string = getAttributedString();  
  3. textLayer.frame = CGRectMake(0, CGRectGetMaxY(view.frame), 200, 200);  
  4. [self.view.layer addSublayer:textLayer];  

CATextLayer可以直接支持NSAttributedString!

-----------------------------------------猥琐的分界线-----------------------------------------

效果图:


源码地址

http://blog.sina.com.cn/s/blog_6cffce7701016k7p.html




2. NSMutableAttributedString/NSAttributedString 富文本设置的一些用法

一、设置UILabel的属性attributedText(NSMutableAttributedString)
<span style="font-size:14px;"><span style="font-family:System;"></span><pre name="code" class="objc">NSString *testStr = @"测试";UILabel *testLab = ...(实例对象)NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];  [ps setAlignment:NSTextAlignmentCenter];  NSDictionary *attribs = @{              NSFontAttributeName: [UIFont fontWithName:@"Microsoft Yahei" size:45],              NSParagraphStyleAttributeName:ps};  NSMutableAttributedString *attributedText =[[NSMutableAttributedString alloc] initWithString:testStr attributes:attribs];  testLab.attributedText = attributedText; </span>

二、设置行距、行间距(NSMutableParagraphStyle)
<span style="font-size:14px;">NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];      paragraphStyle.lineHeightMultiple = 20.f;      paragraphStyle.maximumLineHeight = 25.f;      paragraphStyle.minimumLineHeight = 15.f;      paragraphStyle.firstLineHeadIndent = 20.f;  paragraphStyle.alignment = NSTextAlignmentJustified;    NSDictionary *attributes = @{ </span>
<span style="font-size:14px;">NSFontAttributeName:[UIFont systemFontOfSize:14], </span>
<span style="font-size:14px;">NSParagraphStyleAttributeName:paragraphStyle, </span>
<span style="font-size:14px;">NSForegroundColorAttributeName:[UIColor colorWithRed:76./255. green:75./255. blue:71./255. alpha:1]                                   };   textView.attributedText = [[NSAttributedString alloc]initWithString:content attributes:attributes];  </span>
三、设置对齐方式、折行方式
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentJustified;//设置对齐方式
paragraph.lineBreakMode = NSLineBreakByWordWrapping;

四、NSMutableParagraphStyle、NSAttributedString(简单介绍,详细看API


当然也可以初始化一个NSMutableAttributedString,然后向里面添加文字样式,最后将它赋给textView的AttributedText即可 

  1. NSMutableAttributedString *atr = [[NSMutableAttributedString alloc]initWithString:detail];  
  2.     [atr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, detail.length)];  
  3.     textView.attributedText = atr;  

 

另外,对于textview中的链接样式,同样也可以定制 

  1. NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],  
  2.                                      NSUnderlineColorAttributeName: [UIColor blackColor],  
  3.                                      NSUnderlineStyleAttributeName: @(NSUnderlinePatternDash)};  
  4. self.linkTextAttributes = linkAttributes;  
NSMutableParagraphStyle与NSParagraphStyle包括一下属性
  alignment //对齐方式
  firstLineHeadIndent //首行缩进
  headIndent //缩进
  tailIndent  //尾部缩进
  lineBreakMode  //断行方式
  maximumLineHeight  //最大行高
  minimumLineHeight  //最低行高
  lineSpacing  //行距
  paragraphSpacing  //段距
  paragraphSpacingBefore  //段首空间
  baseWritingDirection  //句子方向
  lineHeightMultiple  //可变行高,乘因数。
  hyphenationFactor //连字符属性
NSString *const NSForegroundColorAttributeName;//值为UIColor,字体颜色,默认为黑色。
NSString *const NSBackgroundColorAttributeName;//值为UIColor,字体背景色,默认没有。
NSString *const NSLigatureAttributeName;//值为整型NSNumber,连字属性,一般中文用不到,在英文中可能出现相邻字母连笔的情况。0为不连笔;1为默认连笔,也是默认值;2在ios 上不支持。
NSString *const NSKernAttributeName;//值为浮点数NSNumber,字距属性,默认值为0。
NSString *const NSStrikethroughStyleAttributeName;//值为整型NSNumber,可取值为
enum {
   NSUnderlineStyleNone = 0×00,
   NSUnderlineStyleSingle = 0×01,
};设置删除线。
NSString *const NSUnderlineStyleAttributeName;//同上。设置下划线。
NSString *const NSStrokeColorAttributeName;//值为UIColor,默认值为nil,设置的属性ForegroundColor。
NSString *const NSStrokeWidthAttributeName;//值为浮点数NSNumber。设置比画的粗细。
NSString *const NSShadowAttributeName;//值为NSShadow,设置比画的阴影,默认值为nil。
NSString *const NSVerticalGlyphFormAttributeName;//值为整型NSNumber,0为水平排版的字,1为垂直排版的


转自:http://www.cnblogs.com/ios8/p/ios-uitextview-person.html
http://blog.sina.com.cn/s/blog_916e0cff0101f4gf.html

0 0
原创粉丝点击