【总结】coreText & TextKit

TextKit,CoreText关系

TextKit属于UIKit framework中

CoreText 更底层

【总结】coreText & TextKit_第1张图片

可以从图中看出,原生的文本控件都是构建在TextKit之上的,使用TextKit进行排版和渲染。而UIWebView是构建在WebKit上的,不能使用TextKit功能。

TextKit

  • TextContainer
  • Layout Manager
  • Text Storage

【总结】coreText & TextKit_第2张图片

使用Text Storage实现文字高亮

// frame
let frame = self.view.bounds

// TextStorage , LayoutManager , TextContainer
let textStorage = NSTextStorage()

let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)

let textContainer = NSTextContainer(size: frame.size)
layoutManager.addTextContainer(textContainer)

textView = UITextView(frame: frame, textContainer: textContainer)

// textView
self.view.addSubview(textView)
textView.editable = false
textView.selectable = false
let txtString = String.txtString(filename: "lorem", filetype: "txt")  // 从文本文件中读取数据

textView.textStorage.replaceCharactersInRange(NSMakeRange(0, 0), withString: txtString)

使用textContainer实现混排

textView.textContainer.exclusionPaths = [circlePath]

CoreText

CTFrame 作为一个整体的画布(Canvas),其中由行(CTLine)组成,而每行可以分为一个或多个小方块(CTRun)

举例:

NSMutableAttributedString *mabstring = [[NSMutableAttributedString alloc]initWithString:@"This is a test of characterAttribute. 中文字符"];
//设置字体属性
CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);
[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)]; 

//设置斜体字
CTFontRef font = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 14, NULL);
[mabstring addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 4)];

//下划线
[mabstring addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];

//下划线颜色
[mabstring addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 4)];

//设置字体简隔 eg:test 
long number = 10;
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
[mabstring addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(10, 4)];

//设置空心字
long number = 2;
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
[mabstring addAttribute:(id)kCTStrokeWidthAttributeName value:(id)num range:NSMakeRange(0, [str length])];
     
//设置空心字颜色
[mabstring addAttribute:(id)kCTStrokeColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [str length])];



 

你可能感兴趣的:(【总结】coreText & TextKit)