1、簡介字體
先看看<CoreText/CoreText.h>裏面有什麼ui
#include <CoreText/CTDefines.h> #include <CoreText/CTFont.h>//字體 #include <CoreText/CTFontCollection.h> #include <CoreText/CTFontDescriptor.h> #include <CoreText/CTFontManager.h> #include <CoreText/CTFontTraits.h> #include <CoreText/CTFrame.h>//位置 #include <CoreText/CTFramesetter.h>//大小 #include <CoreText/CTGlyphInfo.h>//圖形 #include <CoreText/CTLine.h>//行 #include <CoreText/CTParagraphStyle.h>//段落 #include <CoreText/CTRubyAnnotation.h> #include <CoreText/CTRun.h>//着重講下 #include <CoreText/CTRunDelegate.h> #include <CoreText/CTStringAttributes.h>//屬性文本 #include <CoreText/CTTextTab.h> #include <CoreText/CTTypesetter.h> #include <CoreText/SFNTLayoutTypes.h> #include <CoreText/SFNTTypes.h> //版本說明 uint32_t CTGetCoreTextVersion( void ) CT_AVAILABLE(10_5, 3_2); #define kCTVersionNumber10_5 0x00020000 #define kCTVersionNumber10_5_2 0x00020001 #define kCTVersionNumber10_5_3 0x00020002 #define kCTVersionNumber10_5_5 0x00020003 #define kCTVersionNumber10_6 0x00030000 #define kCTVersionNumber10_7 0x00040000 #define kCTVersionNumber10_8 0x00050000 #define kCTVersionNumber10_9 0x00060000 #define kCTVersionNumber10_10 0x00070000 #define kCTVersionNumber10_11 0x00080000
其實富文本是繪製出來的流程以下:
atom
而CTRun能夠這樣理解。以下:spa
哈哈哈 哈哈哈 哈哈哈 哈哈哈,這個幾個字體樣式各不相同,而每個塊相同的都是有一個CTRun來管理。code
因此繪製流程結合上圖ip
1.設置文本屬性內存
2.屬性轉換成須要繪製的內容it
3.繪製路徑內存管理
子類化一個Viewio
MyLablel.h
#import <UIKit/UIKit.h> @interface MyLabel : UIView @property (nonatomic, copy)NSString * text; @end
MyLabel.m
#import "MyLabel.h" #import <CoreText/CoreText.h> @implementation MyLabel - (void)drawRect:(CGRect)rect { NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc]initWithString:self.text]; //添加屬性 NSDictionary * attDic1 = @{NSFontAttributeName : [UIFont systemFontOfSize:30], NSForegroundColorAttributeName :[UIColor greenColor] }; NSDictionary * attDic2 = @{NSFontAttributeName : [UIFont systemFontOfSize:20], NSForegroundColorAttributeName :[UIColor yellowColor] }; //把設置好的屬性加到文本屬性內 //range表示從第幾個字符開始的到第幾個 [attributeString addAttributes:attDic1 range:NSMakeRange(0, 4)]; [attributeString addAttributes:attDic2 range:NSMakeRange(4,self.text.length-4)]; //設置要繪製的內容 釋放 CTFramesetterRef framsestter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeString);//須要強轉下 //繪製路徑 建立路徑請求了 Path記得釋放 CGMutablePathRef path = CGPathCreateMutable(); CGRect bounds = self.bounds; CGPathAddRect(path, NULL, bounds); //轉換成要繪製的內容 釋放 CTFrameRef frame = CTFramesetterCreateFrame(framsestter, CFRangeMake(0, 0), path, NULL); CGContextRef ctx = UIGraphicsGetCurrentContext(); //座標轉換 否則會是倒着的 CGContextTranslateCTM(ctx, 0, self.bounds.size.height); CGContextScaleCTM(ctx, 1, -1); //繪製出來 CTFrameDraw(frame, ctx); //注意這些都市C語言要注意千萬不能忘記內存管理,穿件都是須要釋放 CFRelease(framsestter); CFRelease(frame); CGPathRelease(path); }
ViewController.m
MyLabel * mylabel = [[MyLabel alloc]initWithFrame:self.view.frame]; mylabel.text = @"我是富文本啊 富文本"; [self.view addSubview:mylabel];