標籤:style color os io 使用 ar for 檔案 資料
一、ios5.0以前
1、首先匯入CoreText.framework,並在需要使用的檔案中匯入:
#import<CoreText/CoreText.h>
2、建立一個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;
3、NSAttributedString繼承於NSObject,並且不支援任何draw的方法,那我們就只能自己draw了。寫一個UIView的子類(假設命名為TView),在initWithFrame中把背景色設為透明(self.backgroundColor = [UIColor clearColor]),然後在重寫drawRect方法:
在代碼中我們調整了CTM(current transformation matrix),這是因為Quartz 2D的座標系統不同,Quartz2D的座標系統在左下角
- -(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);
- }
4、另外方法使用
1)
- CATextLayer *textLayer = [CATextLayer layer];
- textLayer.string = getAttributedString();
- textLayer.frame = CGRectMake(0, CGRectGetMaxY(view.frame), 200, 200);
- [self.view.layer addSublayer:textLayer];
CATextLayer可以直接支援NSAttributedString!
2) UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(100, 100, 100, 40);
[label setAttributedText:attrTitle];
[self.view addSubview:label];
二、在iOS6之後,建立一個AttributedString變成了一件輕鬆的事情,<CoreText/CoreText.h>已經不需要匯入了。如果我要設定字型的顏色,可以直接這樣:
[textAttr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, text.length)];
如果要計算一個NSAttributedString的size,使用NSAttributedString的這個API:
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
但是需要注意一點,如果調用這個API的NSAttributedString不包含字型、行高等有利於計算的資料,那最終計算出來的size可能和實際有所出入。
NSMutableAttributedString富文本