CoreText (一)文本显示

239 阅读1分钟

大神链接

1.简单的显示文案
  • 自定义一个UIView,在drawRect方法中实现渲染(#import <CoreText/CoreText.h>)
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    // 坐标系转换
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(contextRef, CGAffineTransformIdentity);
    CGContextTranslateCTM(contextRef, 0.0, self.bounds.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    // 绘制区域
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.bounds);
    // 绘制内容字符串属性
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:18.0],
        NSForegroundColorAttributeName:[UIColor blueColor],
    };
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:@"Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world" attributes:attributes];
    // 创建CTFrame
    CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeStr);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0.0, attributeStr.length), path, NULL);
    // 用CTFrameRef在CGContextRef上下文绘制
    CTFrameDraw(frameRef, contextRef);
}
CoretTextFirstView *testView = [[CoretTextFirstView alloc] initWithFrame:CGRectMake(10.0, 30.0, 200.0, 100.0)];
[self.view addSubview:testView];
  • 效果

Simulator Screen Shot - iPhone 8 - 2021-08-18 at 14.20.29.png