iOS 12奇葩问题之CGContextRef和UIBezierPath冲突

A.m

- (CAShapeLayer *)createIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point {
    
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(0, 0)];
    [bezierPath addLineToPoint:CGPointMake(4, 5)];
    [bezierPath addLineToPoint:CGPointMake(8, 0)];
    [bezierPath stroke];//ios12 崩溃
    
    layer.strokeColor = [kSelectedColor CGColor];
    //设置填充颜色 如果只要边 可以把里面设置成[UIColor ClearColor]
    layer.fillColor = [[UIColor clearColor]CGColor];
    layer.path = bezierPath.CGPath;
    layer.lineWidth = 1.0;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    
    CGPathRelease(bound);
    
    layer.position = point;
    
    return layer;
}

B.m

/*
 *开始绘制
 */
-(void) drawTextInRect:(CGRect)requestedRect
{
    [self initAttributedString];
    
    //排版
    if (attributedString==nil) {
        return;
    }
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
    
    CGMutablePathRef leftColumnPath = CGPathCreateMutable();
    
    CGPathAddRect(leftColumnPath, NULL ,CGRectMake(0 , 0 ,self.bounds.size.width , self.bounds.size.height));
    
    CTFrameRef leftFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), leftColumnPath , NULL);
    
    //翻转坐标系统(文本原来是倒的要翻转下)
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);//别忘了调UIGraphicsPopContext();
    
    CGContextSetTextMatrix(context , CGAffineTransformIdentity);
    CGContextTranslateCTM(context , 0 ,self.bounds.size.height);
    CGContextScaleCTM(context, 1.0 ,-1.0);
    
    //画出文本
    CTFrameDraw(leftFrame,context);
    
    //释放
    CGPathRelease(leftColumnPath);
    CFRelease(framesetter);
//    UIGraphicsPushContext(context);
//    push:UIGraphicsPushContext(context)把context压入栈中,并把context设置为当前绘图上下文
//    pop:UIGraphicsPopContext将栈顶的上下文弹出,恢复先前的上下文,但是绘图状态不变
//    不实现UIGraphicsPopContext();会和 [bezierPath stroke];冲突程序crash
    UIGraphicsPopContext();
}

B.m类中别人写的代码只调用了UIGraphicsPushContext(context);,忘记调用UIGraphicsPopContext();
结果造成了奇葩问题:
当执行B后再执行A,在iOS12中,A.m中调用[bezierPath stroke];时程序crash。
What the fuck!

你可能感兴趣的:(iOS 12奇葩问题之CGContextRef和UIBezierPath冲突)