Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate UIImage in UIImageView Up & Down (Like it's hovering) Loop

Hello I have an image that I'd like to move up and down (Up 10 pixels and down 10 pixels) so that my image appears to be hovering. How can I do this with simple animation thanks so much!!!

like image 393
Year3000 Avatar asked Oct 14 '12 10:10

Year3000


People also ask

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage . Save this answer.

How do I add actions to UIImageView?

Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.

How do you add a UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in . h file and allocated in init method, I need to set image in viewDidLoad method.


2 Answers

For Swift 3, Swift 4 and 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")
like image 186
pableiros Avatar answered Sep 25 '22 10:09

pableiros


You could use Core Animation to animate the position of the views layer. If you configure the animation to be additive you won't have to bother calculating the new absolute position, just the change (relative position).

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

Since this is using Core Animation you will need to add QuartzCore.framework and #import <QuartzCore/QuartzCore.h> into your code.

like image 36
David Rönnqvist Avatar answered Sep 22 '22 10:09

David Rönnqvist