IOS:移动UIImageView

问题描述:

在我的应用程序中,我想移动一个小小的UIImageView在.png中;这是一只小昆虫,我想模拟他的飞行。举例来说,我希望这个PNG在移动一个倒八时作为无限simbol∞IOS:移动UIImageView

您可以使用CoreAnimation。您可以为视图创建子类,为昆虫创建子视图,然后按照定义的路径为其分配动画。

你的UIImageView可以动画。如果它是一只苍蝇,你可以为翼移动做了几帧:

NSArray *images = [NSArray arrayWithObjects:..., nil]; 

insect.animationImages = images; 
insect.animationDuration = ??; 
insect.animationRepeatCount = 0; 
[insect startAnimating]; 

然后为昆虫的初始化帧:

insect.frame = CGRectMake(-120, 310, [[images objectAtIndex:0] size].width, [[images objectAtIndex:0] size].height); 

,然后定义路径:

CGMutablePathRef aPath; 
CGFloat arcTop = insect.center.y - 50; 
aPath = CGPathCreateMutable(); 

CGPathMoveToPoint(aPath, NULL, insect.center.x, insect.center.y); 
CGPathAddCurveToPoint(aPath, NULL, insect.center.x, arcTop, 240, -100, 490, 360); 

CAKeyframeAnimation* arcAnimation = [CAKeyframeAnimation animationWithKeyPath: @"position"]; 
arcAnimation.repeatCount = HUGE_VALF; 
[arcAnimation setDuration: 4.5]; 
[arcAnimation setAutoreverses: NO]; 
arcAnimation.removedOnCompletion = NO; 
arcAnimation.fillMode = kCAFillModeBoth; 
[arcAnimation setPath: aPath]; 
CFRelease(aPath); 
[insect.layer addAnimation: arcAnimation forKey: @"position"]; 

我离开了如何去做无限循环路径:)

希望它有帮助!

+0

我无法做一个循环路径,你能帮助我吗? – CrazyDev

+1

看看这个:http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html //你必须使用两个半圆和两条线(at至少对于更简单的∞版本)。在此图像中:http://twitpic.com/6yynco每条彩色线代表需要创建的路径线。 –

通常情况下,如果你要移动东西,我建议使用[UIView动画...]。但是,您希望在复杂的曲线路径上移动。相反,我建议提出一个公式,给出昆虫的(x,y)作为时间的函数,然后以相当小的时间间隔开始一个NSTimer,并且每次获得更新时,移动昆虫(也许使用[UIView animate ...])。

另一种方法是使用2-d动画框架,例如cocos2d - 然后,您可以获得与帧刷新率链接的'更新'调用,在该更新调用中您更新了昆虫的位置与上面相同的方程。