通过延迟绘图简单动画

时间:2009-03-29 16:35:16

标签: iphone objective-c quartz-2d

我正在尝试为我的iPhone应用程序实现一些非常简单的线条绘制动画。我想在延迟后在我的视线上画一个矩形。我正在使用performSelector来运行我的绘图方法。

-(void) drawRowAndColumn: (id) rowAndColumn
{
    int rc = [rowAndColumn intValue];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
    CGRect rect = CGRectMake(rc * 100, 100, 100, 100);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context, kCGPathFillStroke);

}

然后通过以下方式调用:

int col = 10;
[self performSelector:@selector(drawRowAndColumn:) 
           withObject:[NSNumber numberWithInt:col]
           afterDelay:0.2];

但似乎在实际发送drawRowAndColumn:消息时,它无法再访问有效的CGContextRef,因为我收到错误,例如:

<Error>: CGContextAddRect: invalid context

如果我直接调用performSelector替换drawRowAndColumn,则可以正常使用。所以我的第一个想法是通过CGContextRef传递performSelector,但我似乎无法弄清楚如何同时传递多个参数(这是另一个好问题。)

以上代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

你不能随便那样画画。您需要实现UIView的drawRect:方法并将绘图代码放在那里。 要让drawRect:解雇,你需要让Cocoa知道需要绘制视图。为此,您可以拨打setNeedsDisplaysetNeedsDisplayInRect:

直接翻译你的尝试,你可以使用performSelector调用setNeedsDisplay:withObject:afterDelay - 但这可能不是一个很好的动画制作方法。

这取决于你真正想要做的事情 - 但是你可以考虑,例如,按照我的建议把你的绘图代码放在drawRect中,但是隐藏起来。然后你可以调用setHidden:NO使用performSelector让它在延迟后显示 - 或者你可以通过开始不隐藏来平滑地设置动画,但是使用0的alpha,然后在UIView动画块中将alpha更改为1(有很多关于这在文档中。)