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

ztmd8pv5  于 2023-05-23  发布在  iOS
关注(0)|答案(2)|浏览(191)

我尝试使用以下代码在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.

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

[aPath fill];

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

tv6aics1

tv6aics11#

该错误意味着您没有要将路径绘制到的上下文,而您必须有一个上下文。
由于这段代码是在视图控制器中,因此您需要决定应该绘制到哪个上下文中。
您可以自己创建一个上下文并将路径绘制到其中,这将是有益的,例如,如果您想要创建包含路径的图像。这将使用CGBitmapContextCreate完成。
或者,可能更多的是您正在寻找的,通过将路径绘制到视图控制器的视图上下文中。这在drawRect:方法中可用。因此,您可以在自定义视图子类中实现它,并将代码移到那里。
另一种方法是使用CAShapeLayer,使用路径(使用CGPath)创建,并将其添加为视图控制器视图层的子层。那你就完全不用担心上下文了

lmyy7pcs

lmyy7pcs2#

下面是一个示例,说明如何使用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)
}

相关问题