UILabel上展示不同颜色的文字(NSAttributedString)

http://blog.csdn.net/u011439689/article/details/22693679


【提示:最好的方法在最后哦!O(∩_∩)O~】

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

#import<CoreText/CoreText.h>

新建一个类,继承UILabel,以下为文件内容:

MyLabel.h

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //MyLabel.h  
  2. #import <Foundation/Foundation.h>  
  3. #import <CoreText/CoreText.h>  
  4.   
  5. @interface MyLabel : UILabel  
  6.   
  7. @end  

MyLabel.m

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //MyLabel.m  
  2. #import "MyLabel.h"  
  3.   
  4. @implementation MyLabel  
  5.   
  6. //NSAttributedString继承于NSObject,并且不支持任何draw的方法,那我们就只能自己draw了。  
  7. -(void)drawRect:(CGRect)rect{  
  8.   
  9.     [super drawRect:rect];  
  10.       
  11.     NSAttributedString *attriString = [self getAttributedString];  
  12.       
  13.     //在代码中我们调整了CTM(current transformation matrix),这是因为Quartz 2D的坐标系统不同  
  14.     CGContextRef ctx = UIGraphicsGetCurrentContext();  
  15.     CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));  
  16.       
  17.     //CTFramesetter是CTFrame的创建工厂,NSAttributedString需要通过CTFrame绘制到界面上,得到CTFramesetter后,创建path(绘制路径),然后得到CTFrame,最后通过CTFrameDraw方法绘制到界面上。  
  18.     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);  
  19.     CGMutablePathRef path = CGPathCreateMutable();  
  20.     CGPathAddRect(path, NULL, rect);  
  21.     CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(00), path, NULL);  
  22.     CFRelease(path);  
  23.     CFRelease(framesetter);  
  24.       
  25.     CTFrameDraw(frame, ctx);  
  26.     CFRelease(frame);  
  27.   
  28.     /* 
  29.      //------------------------------------------------------------------------ 
  30.      //----------------取消注释,同样可以实现UILabel上展示不同样式的文字-------------- 
  31.      //------------------------------------------------------------------------ 
  32.      CATextLayer *textLayer = [CATextLayer layer]; 
  33.      textLayer.string = [self getAttributedString]; 
  34.      textLayer.frame = CGRectMake(0, 50, 200, 200);//可调整位置 
  35.      textLayer.backgroundColor = [UIColor purpleColor].CGColor; 
  36.      [self.layer addSublayer:textLayer]; 
  37.      */  
  38. }  
  39.   
  40. -(NSMutableAttributedString *)getAttributedString{  
  41.     //创建一个NSMutableAttributedString  
  42.     NSMutableAttributedString *attriString = [[[NSMutableAttributedString alloc] initWithString:@"Come on,baby!Come on,baby!Come on,baby!"]autorelease];  
  43.     //把this的字体颜色变为红色  
  44.     [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  45.                         value:(id)[UIColor redColor].CGColor  
  46.                         range:NSMakeRange(04)];  
  47.     //把is变为黄色  
  48.     [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  49.                         value:(id)[UIColor yellowColor].CGColor  
  50.                         range:NSMakeRange(516)];  
  51.     //改变this的字体,value必须是一个CTFontRef  
  52.     [attriString addAttribute:(NSString *)kCTFontAttributeName  
  53.                         value:(id)CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName,14,NULL)  
  54.                         range:NSMakeRange(04)];  
  55.     //给this加上下划线,value可以在指定的枚举中选择  
  56.     [attriString addAttribute:(NSString *)kCTUnderlineStyleAttributeName  
  57.                         value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble]  
  58.                         range:NSMakeRange(04)];  
  59.       
  60.     /* 
  61.      换行的实现 
  62.       
  63.      如果想要计算NSAttributedString所要的size,就需要用到这个API: 
  64.      CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行时会算不准的,因为在CoreText里,行间距也是你来控制的。 
  65.      设置行间距和换行模式都是设置一个属性:kCTParagraphStyleAttributeName,这个属性里面又分为很多子 
  66.      属性,其中就包括 
  67.      kCTLineBreakByCharWrapping 
  68.      kCTParagraphStyleSpecifierLineSpacingAdjustment 
  69.      设置如下: 
  70.     */  
  71.       
  72.       
  73.     /* 
  74.      //-------------取消注释,实现换行------------- 
  75.       
  76.      CTParagraphStyleSetting lineBreakMode; 
  77.      CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //换行模式 
  78.      lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode; 
  79.      lineBreakMode.value = &lineBreak; 
  80.      lineBreakMode.valueSize = sizeof(CTLineBreakMode); 
  81.      //行间距 
  82.      CTParagraphStyleSetting LineSpacing; 
  83.      CGFloat spacing = 4.0;  //指定间距 
  84.      LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment; 
  85.      LineSpacing.value = &spacing; 
  86.      LineSpacing.valueSize = sizeof(CGFloat); 
  87.       
  88.      CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing}; 
  89.      CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2);   //第二个参数为settings的长度 
  90.      [attriString addAttribute:(NSString *)kCTParagraphStyleAttributeName 
  91.      value:(id)paragraphStyle 
  92.      range:NSMakeRange(0, attriString.length)]; 
  93.      */  
  94.       
  95.     return attriString;  
  96. }  
  97.   
  98. @end  

测试代码

先要 #import "MyView.h",在适当位置创建MyLabel的对象,并添加到View中

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. MyLabel *myLabel = [[MyLabel alloc]initWithFrame:CGRectMake(100100100100)];  
  2. [self.view addSubview:myLabel];  
  3. [myLabel release];  

效果图如下:




补充:另一种方式,利用NSMutableAttributedString,很简便

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //iOS6以后 在UILabel显示不同的字体和颜色  
  2. NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];  
  3. [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];  
  4. [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];  
  5. [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];  
  6. [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(05)];  
  7. [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0] range:NSMakeRange(612)];  
  8. [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(196)];  
  9. self.attrLabel.attributedText = str;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值