绘制 UIBezierPath 时出现无效内容错误



我正在尝试使用以下代码在viewdidload中制作一个简单的圆圈:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100,100) radius:100 startAngle:M_PI/6 endAngle:M_PI clockwise:YES];

    [aPath fill];
}

我收到以下错误:

CGContextSaveGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

我知道这个问题已经在这里讨论过了,但我不能联系。错误发生在

[aPath fill];

这是否与应用程序生命周期有关?

该错误意味着您没有要将路径绘制到的上下文,并且必须有一个上下文。

由于此代码位于视图控制器中,因此您需要决定应绘制到哪个上下文中。

您可以自己创建上下文并将路径绘制到其中,例如,如果要创建包含路径的图像,这将是有益的。这将使用 CGBitmapContextCreate .

或者,可能还有更多您正在寻找的内容,方法是将路径绘制到视图控制器视图上下文中。这在drawRect:方法中可用。因此,您将在自定义视图子类中实现它,并将代码移动到那里。

另一种方法是使用 CAShapeLayer ,使用路径(使用 CGPath )创建,并将其添加为视图控制器视图层的子层。那么你根本不需要担心上下文...

下面是如何使用 CAShapeLayer()UIBezierPath() 在没有 drawRect() 的情况下进行绘制的示例 在没有上下文的情况下,不要使用 UIColor.setStroke() 设置颜色,也不要使用 path.stroke(),因为在将路径分配给 shapeLayer 时隐含了笔触操作。

func addDiagonalLineLayer() {
    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.green.cgColor
    let path = UIBezierPath()
    path.lineWidth = 1.0
    path.move(to:    CGPointMake(0, 0))
    path.addLine(to: CGPointMake(maxW, maxH))
    shapeLayer.path = path.cgPath
    view.layer.addSublayer(shapeLayer)
}

最新更新