请设置CG_CONTEXT_SHOW_BACKTRACE环境变量

31i*_*i45 8 cocoa-touch objective-c uibezierpath

尽管关于这个问题超过了3个帖子(2015年制作),但是我已经解决了这个问题.

当我运行时,一个简单的代码使用UIBezierPath绘制一条线程序将返回给我:

:CGContextSetStrokeColorWithColor:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetFillColorWithColor:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSaveGState:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetLineWidth:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetLineJoin:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetLineCap:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetMiterLimit:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextSetFlatness:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextAddPath:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextDrawPath:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

:CGContextRestoreGState:无效的上下文0x0.如果要查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量.

@interface line : UIView
UIBezierPath *myPath;
.........
@implementation
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint touchLocation = [touch locationInView:self];
myPath = [UIBezierPath bezierPath];
[myPath moveToPoint:touchLocation];
}
- (void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint touchLocation = [touch locationInView:self];
[myPath addLineToPoint:touchLocation];
[[UIColor blackColor]setStroke];
[[UIColor greenColor]setFill];
[myPath stroke];
}
Run Code Online (Sandbox Code Playgroud)

如果我要使用drawRect绘制

- (void) drawRect:(CGRect)rect {
....
}
Run Code Online (Sandbox Code Playgroud)

不会弹出任何错误.我在想,如果我收到这些错误,因为touchesBegantouchesMoved不能执行绘图?

在我曾经使用的可可(OS X)中setNeedsDisplay,但它在可可触摸中不存在.

我要问的是,无论如何要删除这些错误,还是UIBezierPath在运行时有另一种绘制方式.

Bor*_*kyi 16

发生无效的上下文错误,因为您尝试在drawRect:方法之外使用绘图操作,因此不会设置当前的图形上下文.

与OS X一样,您应该在drawRect:方法中执行绘图,并使用setNeedsDisplay更新生成的图像.无一不setNeedsDisplaysetNeedsDisplayInRect:方法可用于iOS上的UIView.

所以,结果应如下所示:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint touchLocation = [touch locationInView:self];
myPath = [UIBezierPath bezierPath];
[myPath moveToPoint:touchLocation];
}

- (void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint touchLocation = [touch locationInView:self];
[myPath addLineToPoint:touchLocation];
[self setNeedsDisplay];
}

- (void) drawRect:(CGRect)rect {
[[UIColor blackColor]setStroke];
[[UIColor greenColor]setFill];
[myPath stroke];
}
Run Code Online (Sandbox Code Playgroud)