YYText,iOS 17上触发断言导致崩溃的解决办法

551 阅读1分钟

YYText是我们iOS开发中常用的一个开源第三方组件,原作者已停止维护,在最新的iOS17上会触发断言崩溃:

UIGraphicsBeginImageContext() failed to allocate CGBitampContext: size={382, 0}, scale=3.000000, bitmapInfo=0x2002. Use UIGraphicsImageRenderer to avoid this assert.

原因是UIGraphicsBeginImageContext在iOS 17上已经deprecated了,如果项目中暂时无法移除YYText,可以尝试使用下面的方法进行修复

1、移出YYText在cocopads中的引用:

# pod "YYText"

2、手动导入YYText

3、将

UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, self.contentsScale);  
CGContextRef context = UIGraphicsGetCurrentContext();  
if (self.opaque) {  
CGSize size = self.bounds.size;  
size.width *= self.contentsScale;  
size.height *= self.contentsScale;  
CGContextSaveGState(context); {  
if (!self.backgroundColor || CGColorGetAlpha(self.backgroundColor) < 1) {  
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);  
CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));  
CGContextFillPath(context);  
}  
if (self.backgroundColor) {  
CGContextSetFillColorWithColor(context, self.backgroundColor);  
CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));  
CGContextFillPath(context);  
}  
} CGContextRestoreGState(context);  
}  
task.display(context, self.bounds.size, ^{return NO;});  
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
UIGraphicsEndImageContext();  
self.contents = (__bridge id)(image.CGImage);

替换为

    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];  
    format.opaque = self.opaque;  
    format.scale = self.contentsScale;
    
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:self.bounds.size format:format];
    UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
        CGContextRef context = rendererContext.CGContext;
        if (self.opaque) {
            CGSize size = self.bounds.size;
            size.width *= self.contentsScale;
            size.height *= self.contentsScale;
            CGContextSaveGState(context); {
                if (!self.backgroundColor || CGColorGetAlpha(self.backgroundColor) < 1) {
                    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
                    CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
                    CGContextFillPath(context);
                }
                if (self.backgroundColor) {
                    CGContextSetFillColorWithColor(context, self.backgroundColor);
                    CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
                    CGContextFillPath(context);
                }
            } CGContextRestoreGState(context);
        }
        task.display(context, self.bounds.size, ^{return NO;});
    }];

    self.contents = (__bridge id)(image.CGImage);

再重新运行项目即可。

原文链接:github.com/ibireme/YYT…