Reputation:
I want to move my image view from left to the center of the view.
Following is my code:
CGPoint origin = self.headerImage.center;
CGPoint target = CGPointMake(0, self.headerImage.center.x);
CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"position.x"];
bounce.fromValue = [NSNumber numberWithInt:origin.x];
bounce.toValue = [NSNumber numberWithInt:target.x];
[self.headerImage.layer addAnimation:bounce forKey:@"position"];
It has to start moving from the left and stop at the center when the view controller is loaded. But it is not working properly. How can I sort this out?
Upvotes: 0
Views: 124
Reputation: 6040
The problem is here :
CGPoint origin = self.headerImage.center;
CGPoint target = CGPointMake(0, self.headerImage.center.x);
You're not aiming at the correct target, you're aiming at the current center of your headerImage
; so technically, origin
and target
are the same location here.
Move the target to the center of the superview, and you'll be good :)
CGPoint target = CGPointMake(0, self.headerImage.superView.center.x);
You could also probably use self.view.center.x
, but it's slightly less future proof.
Also, I've noticed the keys you're using differ between the two times you use it ("position" and "position.x"). I'm not super comfortable with CAAnimations, so this might be completely right in the first place
Upvotes: 1
Reputation: 3484
target
needs to indicate the center of the view: CGPointMake(self.view.center.x, self.view.center.y)
fillMode
removedOnCompletion
autoreverses
repeatCount
to avoid frame changes (final of animation)Final code:
CGPoint origin = self.headerImage.center;
CGPoint target = CGPointMake(self.view.center.x, self.view.center.y);
CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"position.x"];
bounce.duration = 1;
bounce.fromValue = [NSNumber numberWithInt:origin.x];
bounce.toValue = [NSNumber numberWithInt:target.x];
bounce.fillMode = kCAFillModeForwards;
bounce.removedOnCompletion = NO;
bounce.autoreverses = NO;
bounce.repeatCount = 0;
[self.headerImage.layer addAnimation:bounce forKey:@"position"];
CGAffineTransform transform = CGAffineTransformMakeScale(1.3, 1.3);
self.headerImage.transform = transform;
Upvotes: 1
Reputation: 8049
Use
[UIView animateWithDuration:1.0 animations:^{
headerImage.frame = myNewFrameRect;
}];
Upvotes: 1