繁体   English   中英

iOS:如何沿正弦曲线对图像进行动画处理?

[英]iOS: How to animate an image along a sine curve?

如标题中所述,我想使用CG / CA或OpenGL(如果需要)为UIView中从底部到顶部沿正弦曲线传播的一些气泡设置动画。

这是我的CA代码片段,效果很好,但这是一条经过动画处理的直线。 如何建立正弦曲线行为?

- (void)animateBubble:(UIImageView *)imgView {
    [UIView beginAnimations:[NSString stringWithFormat:@"%i",imgView.tag] context:nil];
    [UIView setAnimationDuration:6];
    [UIView setAnimationDelegate:self];
    imgView.frame = CGRectMake(imgView.frame.origin.x, 0, imgView.frame.size.width, imgView.frame.size.height);
    [UIView commitAnimations];
}

我已经实现了与SpriteKit想要的结果(看看: http://youtu.be/Gnj3UAD3gQI )。 气泡沿着正弦曲线从底部到顶部传播,幅度在随机范围内。 此外,我使用陀螺仪传感器来另外影响路径。

UIKit,CG,CA是否可以以某种方式重现此行为(如果绝对必要,OpenGL也可以重现)? 代码示例将是很棒的,但是任何其他想法也将受到高度赞赏。

要沿路径设置动画,首先需要定义该路径。 如果您确实需要一个真正的正弦曲线,我们可以向您展示如何做,但是使用两个二次贝塞尔曲线定义一个近似正弦曲线的方法可能是最简单的:

CGFloat width = ...
CGFloat height = ...
CGPoint startPoint = ...

CGPoint point = startPoint;
CGPoint controlPoint = CGPointMake(point.x + width / 4.0, point.y - height / 4.0);
CGPoint nextPoint = CGPointMake(point.x + width / 2.0, point.y);

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:point];
[path addQuadCurveToPoint:nextPoint controlPoint:controlPoint];

point = nextPoint;
controlPoint = CGPointMake(point.x + width / 4.0, point.y + height / 4.0);
nextPoint = CGPointMake(point.x + width / 2.0, point.y);

[path addQuadCurveToPoint:nextPoint controlPoint:controlPoint];

路径如下所示:

在此处输入图片说明

显然,将startPointwidthheight更改为所需的值。 或者,如果需要更多的迭代,则重复添加更多贝塞尔曲线路径的过程。

无论如何,已经定义了路径,而不是渲染路径本身,您可以创建CAKeyframeAnimation来使UIView沿该路径的position动画化:

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
animation.duration = 1.0;
animation.path = path.CGPath;
[view.layer addAnimation:animation forKey:@"myPathAnimation"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM