storyboard:
新建一个CTDisplayView:UIView
代码如下:
#import "CTDisplayView.h"
#import "CoreText/CoreText.h"
@implementation CTDisplayView
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
//1获取图文上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//2将坐标系上下翻转(由于底层绘制引擎是左下角(0,0),和UIKit坐标系左上角(0,0)相反,所以必须倒转让它重合正常显示)
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//创建绘制的区域,简单地将整个UIVIEW的整个界面作为排版的区域
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
//4设置绘制内容
NSAttributedString *attString = [[NSAttributedString alloc]initWithString:@"Hello World"];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [attString length]), path, NULL);
//展示在图层上
CTFrameDraw(frame, context);
//释放对象
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
}
@end
在storyboard里面拖进一个UIView放在中间,改class为CTDisplayView运行即可。