?NSAttributedString NSAttributedString 可以將一段文字中的部分文字設(shè)置單獨(dú)的字體和顏色承绸。 與UITouch結(jié)合可以實(shí)現(xiàn)點(diǎn)擊不同文字觸發(fā)不同事件的交互功能吱雏。 主要方法: - (void)addAttribute:
(1) NSAttributedString
NSAttributedString 可以將一段文字中的部分文字設(shè)置單獨(dú)的字體和顏色。
與UITouch結(jié)合可以實(shí)現(xiàn)點(diǎn)擊不同文字觸發(fā)不同事件的交互功能。
主要方法:
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
可以設(shè)置某段文字的字體名稱姨谷,顏色谅猾,下滑線等信息。
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
移除之前設(shè)置的字體屬性值嫉拐。
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
存儲某段文字包含的信息(包括字體屬性或其它哩都,也可以存儲一些自定義的信息)
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;
通過location來獲取某段文字中之前存儲的信息NSDictionary
//設(shè)置字體
CTFontRef aFont = CTFontCreateWithName((CFStringRef)textFont.fontName, textFont.pointSize, NULL);
if (!aFont) return;
CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits(aFont, 0.0, NULL, kCTFontItalicTrait, kCTFontBoldTrait); ???//將默認(rèn)黑體字設(shè)置為其它字體
[self removeAttribute:(NSString*)kCTFontAttributeName range:textRange];
[self addAttribute:(NSString*)kCTFontAttributeName value:(id)newFont range:textRange];
CFRelease(aFont);
CFRelease(newFont);
//設(shè)置字體顏色
[self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:textRange];
[self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:textRange];
//設(shè)置對齊 換行
CTTextAlignment coreTextAlign = kCTLeftTextAlignment;
CTLineBreakMode coreTextLBMode = kCTLineBreakByCharWrapping;
CTParagraphStyleSetting paraStyles[2] =
{
{.spec = kCTParagraphStyleSpecifierAlignment, .valueSize = sizeof(CTTextAlignment), .value = http://www.cnblogs.com/lingzhiguiji/p/(const void*)&coreTextAlign},
{.spec = kCTParagraphStyleSpecifierLineBreakMode, .valueSize = sizeof(CTLineBreakMode), .value = http://www.cnblogs.com/lingzhiguiji/p/(const void*)&coreTextLBMode},
};
CTParagraphStyleRef aStyle = CTParagraphStyleCreate(paraStyles, 2);
[self removeAttribute:(NSString*)kCTParagraphStyleAttributeName range:textRange];
[self addAttribute:(NSString*)kCTParagraphStyleAttributeName value:(id)aStyle range:textRange];
CFRelease(aStyle);
(2)Draw NSAttributedString
CGContextRef cgc = UIGraphicsGetCurrentContext();
CGContextSaveGState(cgc);
//圖像方向轉(zhuǎn)換
CGContextConcatCTM(cgc, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f));
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)weiBoText);
drawingRect = self.bounds;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, drawingRect);
textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);
CGPathRelease(path);
CFRelease(framesetter);
CTFrameDraw(textFrame, cgc);
CGContextRestoreGState(cgc);
(3)圖文混排
CTFrameRef ?textFrame ????// coreText 的 frame
CTLineRef ?????line ????????????// ?coreText 的 line
CTRunRef ?????run ????????????// ?line ?中的部分文字