NSAttributedString NSAttributedString 可以将一段文字中的部分文字设置单独的字体和颜色。 与UITouch结合可以实现点击不同文字触发不同事件的交互功能。 主要方法: - (void)addAttribute:
(1) NSAttributedString
NSAttributedString 可以将一段文字中的部分文字设置单独的字体和颜色。
与UITouch结合可以实现点击不同文字触发不同事件的交互功能。
主要方法:
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
可以设置某段文字的字体名称,颜色,下滑线等信息。
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
移除之前设置的字体属性值。
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
存储某段文字包含的信息(包括字体属性或其它,也可以存储一些自定义的信息)
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;
通过location来获取某段文字中之前存储的信息NSDictionary
//设置字体
CTFontRef aFont = CTFontCreateWithName((CFStringRef)textFont.fontName, textFont.pointSize, NULL);
if (!aFont) return;
CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits(aFont, 0.0, NULL, kCTFontItalicTrait, kCTFontBoldTrait); //将默认黑体字设置为其它字体
[self removeAttribute:(NSString*)kCTFontAttributeName range:textRange];
[self addAttribute:(NSString*)kCTFontAttributeName value:(id)newFont range:textRange];
CFRelease(aFont);
CFRelease(newFont);
//设置字体颜色
[self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:textRange];
[self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:textRange];
//设置对齐 换行
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);
//图像方向转换
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 中的部分文字