ios - 使用核心文本输出字符串

标签 ios core-text

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/

相关文章:

ios - 如何在iOS的AWS Lambda中发送请求 header 数据

android - 使用什么类型的小部件可以让用户将 Excel 文件上传到 Flutter 应用程序?

iphone - ASIFormDataRequest NSInvalidArgumentException 异常

multithreading - 在非主线程中使用不使用 CGContextRef 的 iOS CoreText API

ios - 如何显示一个 ViewController 然后关闭它以显示一个 UISplitViewController?

ios - 如何在 Carto Mobile Swift 中使用固定标记针在后台移动 map

ios - 标签下划线不显示

iphone - Objective C/iPhone 中普通空间的 ASCII 值

ios - Core Text 有时无法生成结果 [iOS]

swift - 在 UITextField 中输入的每个数字周围绘制方框