我正在尝试在外部类中设置一个如下所示的方法:
myClass.m
- (void)drawSomeStuffInContext:(CGContextRef)context atStartingPoint:(CGPoint *)coords
{
//draw some stuff (ignoring coords for now)
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 1.0f);
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 100, 50);
CGContextStrokePath(context);
}
viewController.m
- (void)viewDidLoad
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGPoint startCoords = CGPointMake(100.0, 100.0);
[[myClass alloc] drawSomeStuffInContext:currentContext atStartingPoint:startCoords];
}
项目构建并运行,但我在日志中收到以下错误,但没有绘制任何内容:
[...] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
[...] <Error>: CGContextSetLineWidth: invalid context 0x0
[...] <Error>: CGContextMoveToPoint: invalid context 0x0
[...] <Error>: CGContextAddLineToPoint: invalid context 0x0
[...] <Error>: CGContextDrawPath: invalid context 0x0
我一直在网上搜索类似的问题/示例,但没有运气。是否需要不同的/附加参数?我应该从viewDidLoad
以外的其他地方调用 draw 方法吗?非常感谢建议!
drawRect 没有被调用(据我所知),这意味着根本没有绘制视图。你应该调用类似 [super initWithFrame:frame];
的东西,其中框架是 CGRect(显然)在 drawSomeStuffInContext 方法中。
或者,你可以在viewController.m的viewDidLoad方法中调用[[myClass alloc] initWithFrame:frame];并将起点存储在全局变量中。