【问题标题】:iOS: How to animate an image along a sine curve?iOS:如何沿正弦曲线为图像设置动画?
【发布时间】:2015-09-17 04:28:27
【问题描述】:

如标题所述,我想在 UIView 中使用 CG/CA 或什至 OpenGL(如有必要)为一些沿着正弦曲线从底部到顶部行进的气泡设置动画。

这是我的 CA 代码 sn-p 工作正常,但它是一条动画直线。如何构建正弦曲线行为?

- (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)?代码示例会很棒,但也非常感谢任何其他想法。

【问题讨论】:

    标签: ios objective-c uiview core-graphics core-animation


    【解决方案1】:

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

    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 沿该路径动画UIViewposition

    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"];
    

    【讨论】:

    • 非常感谢您的回答,对于我迟到的回复感到抱歉。我正在寻找一种解决方案来实现与我使用 SpriteKit 制作的视频中相同的结果,但我现在需要将其迁移到 UIKit/CG/CA。请看一下:youtu.be/Gnj3UAD3gQI 我也在尝试改进我原来的问题。
    • 好的,我在原来的问题中添加了更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2012-11-16
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多