使用CoreAnimation为动画设置动画

nut*_*ler 15 iphone cocoa-touch core-animation core-graphics

我接近核心动画和经验绘图.我试图动画一个简单的形状; 所讨论的形状由3条线加上贝塞尔曲线组成.还绘制了一条红线,以显示曲线控制点.

替代文字http://img.skitch.com/20091119-1ufar435jdq7nwh8pid5cb6kmm.jpg

我的主控制器只需添加此子视图并随时调用该adjustWave方法touchesEnd.这是我的形状绘图类的代码.如您所见,该类有一个属性cp1x(贝塞尔控制点1的x).这是我想要动画的价值.记住,这是一个愚蠢的尝试......

- (void)drawRect:(CGRect)rect {
    float cp1y = 230.0f;
    float cp2x = 100.0f;
    float cp2y = 120.0f;

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextClearRect(ctx, rect);

    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathMoveToPoint(path, NULL, 10.0f, 200.0f); 
    CGPathAddCurveToPoint (path, NULL, cp1x, cp1y, cp2x, cp2y, 300.0f, 200.0f);
    CGPathAddLineToPoint(path, NULL, 300.0f, 300.0f); 
    CGPathAddLineToPoint(path, NULL, 10.0f, 300.0f); 
    CGPathCloseSubpath(path); 
    CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor); 
    CGContextAddPath(ctx, path); 
    CGContextFillPath(ctx);

    // Drawing a line from control points 1 and 2
    CGContextBeginPath(ctx);
    CGContextSetRGBStrokeColor(ctx,1,0,0,1);
    CGMutablePathRef cp1 = CGPathCreateMutable(); 
    CGPathMoveToPoint(cp1, NULL, cp1x, cp1y); 
    CGPathAddLineToPoint(cp1, NULL, cp2x, cp2y); 
    CGPathCloseSubpath(cp1); 
    CGContextAddPath(ctx, cp1); 
    CGContextStrokePath(ctx);
}

- (void)adjustWave {
    [UIView beginAnimations:@"movement" context:nil]; 
    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationWillStartSelector:@selector(didStart:context:)]; 
    [UIView setAnimationDidStopSelector:@selector(didStop:finished:context:)]; 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:3.0f]; 
    [UIView setAnimationRepeatCount:3]; 
    [UIView setAnimationRepeatAutoreverses:YES]; 
    cp1x = cp1x + 20.0f;
    [UIView commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)

形状不会改变.相反,如果我取出CA代码并在最后一个方法中添加一个简单的`[self setNeedsDisplay],那么形状会发生变化,但很明显没有CA. 你能帮助涂抹吗?我相信我在这里犯了一个非常基本的错误......在此先感谢Davide

Bra*_*son 18

如果你是为iPhone OS 3.x(或Snow Leopard)编写这个,那么新的CAShapeLayer类应该可以让你很容易地做这种动画.如果您的路径保持相同数量的控制点(如您的情况),则可以将该路径设置为CAShapeLayer,然后将path属性从该起始值设置为最终路径.核心动画将对路径中的控制点执行适当的插值,以在这两种状态之间设置动画(如果使用CAKeyframeAnimation,则更多).

请注意,这是一个图层,因此您需要将其添加为UIView的子图层.此外,我不认为path属性隐式动画,因此您可能需要手动创建CABasicAnimation以设置从路径1到路径2的形状变化的动画.

编辑(2009年11月21日):Joe Ricioppo 在这里有一篇关于CAShapeLayer的精彩文章,包括一些展示这类动画的视频.