IOS CGContext文档说现在不推荐使用各种字符串输出函数来支持核心文本。文档只是说"使用核心文本。"
如果我有
NSString *string ;
将该文本绘制到CGContext的简单的,目前批准的方法是什么?
答案 0 :(得分:2)
这是我重写的drawRect:
方法,用于呈现内部包含所有解释注释的属性字符串。调用此方法时,UIKit已为您的视图正确配置了绘图环境,您只需调用渲染内容所需的绘图方法和功能。
/*!
* @abstract draw the actual coretext on the context
*
*/
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self.backgroundColor setFill];
CGContextFillRect(context, rect);
if (_ctframe != NULL) CFRelease(_ctframe);
if (_framesetter != NULL) CFRelease(_framesetter);
//Creates an immutable framesetter object from an attributed string.
//Use here the attributed string with which to construct the framesetter object.
_framesetter = CTFramesetterCreateWithAttributedString((__bridge
CFAttributedStringRef)self.attributedString);
//Creates a mutable graphics path.
CGMutablePathRef mainPath = CGPathCreateMutable();
if (!_path) {
CGPathAddRect(mainPath, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
} else {
CGPathAddPath(mainPath, NULL, _path);
}
//This call creates a frame full of glyphs in the shape of the path
//provided by the path parameter. The framesetter continues to fill
//the frame until it either runs out of text or it finds that text
//no longer fits.
CTFrameRef drawFrame = CTFramesetterCreateFrame(_framesetter, CFRangeMake(0, 0),
mainPath, NULL);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw text
CTFrameDraw(drawFrame, context);
//clean up
if (drawFrame) CFRelease(drawFrame);
CGPathRelease(mainPath);
}