IOS CGContext 文档表示,现在已弃用各种字符串输出函数,转而使用核心文本。文档只是说“使用核心文本代替。”
如果我有
NSString *string ;
当前批准的将该文本绘制到 CGContext 的简单方法是什么?
最佳答案
这是我重写的 drawRect:
方法,用于呈现属性字符串,其中包含所有解释注释。调用此方法时,UIKit 已为您的 View 配置了适当的绘图环境,您可以简单地调用渲染内容所需的任何绘图方法和函数。
/*!
* @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);
}
关于ios - 使用核心文本输出字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23191331/