0

我正在尝试在外部类中设置一个方法,如下所示:

我的班级.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);
}

视图控制器.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

我一直在网上搜索类似的问题/示例,但没有运气。是否需要不同的/附加参数?我应该从其他地方调用 draw 方法viewDidLoad吗?非常感谢您的建议!

4

1 回答 1

1

drawRect 没有被调用(据我所知)这意味着视图根本没有被绘制。您应该[super initWithFrame:frame];在 drawSomeStuffInContext 方法中调用类似 where frame is a CGRect (显然)的东西。

或者你可以调用 [[myClass alloc] initWithFrame:frame]; 在 viewController.m 的 viewDidLoad 方法中,并将起点存储在全局变量中。

于 2012-06-29T10:24:36.130 回答