10

您好,我有一个图像,我想上下移动(上移 10 像素和下移 10 像素),以便我的图像看起来是悬停的。我怎么能用简单的动画做到这一点非常感谢!!!

4

4 回答 4

25

您可以使用 Core Animation 为视图层的位置设置动画。如果您将动画配置为,additive您将不必费心计算新的绝对位置,只需更改(相对位置)。

CABasicAnimation *hover = [CABasicAnimation animationWithKeyPath:@"position"];
hover.additive = YES; // fromValue and toValue will be relative instead of absolute values
hover.fromValue = [NSValue valueWithCGPoint:CGPointZero];
hover.toValue = [NSValue valueWithCGPoint:CGPointMake(0.0, -10.0)]; // y increases downwards on iOS
hover.autoreverses = YES; // Animate back to normal afterwards
hover.duration = 0.2; // The duration for one part of the animation (0.2 up and 0.2 down)
hover.repeatCount = INFINITY; // The number of times the animation should repeat
[myView.layer addAnimation:hover forKey:@"myHoverAnimation"];

由于这是使用 Core Animation,您需要将 QuartzCore.framework 添加#import <QuartzCore/QuartzCore.h>到您的代码中。

于 2012-10-14T14:08:30.233 回答
9

对于 Swift 3、Swift 4 和 Swift 5:

let hover = CABasicAnimation(keyPath: "position")
    
hover.isAdditive = true
hover.fromValue = NSValue(cgPoint: CGPoint.zero)
hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: 100.0))
hover.autoreverses = true
hover.duration = 2
hover.repeatCount = Float.infinity
    
myView.layer.add(hover, forKey: "myHoverAnimation")
于 2016-07-29T16:53:53.807 回答
5

试试这个:

CGRect frm_up = imageView.frame;
frm_up.origin.y -= 10;

[UIView animateWithDuration:0.5
    delay:0.0
    options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeats
    animations:^{
        imageView.frame = frm_up;
    }
    completion:NULL
];
于 2012-10-14T10:10:22.260 回答
0

对于这样的任务,最好将图像放置在 的子层中UIView,然后为该子层帧设置动画。本教程可以给你一些想法:http ://www.raywenderlich.com/2502/introduction-to-calayers-tutorial

于 2012-10-14T10:06:11.460 回答