[英]Moving a UIImageView from left to center
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?
我该如何解决呢?
Use 采用
[UIView animateWithDuration:1.0 animations:^{
headerImage.frame = myNewFrameRect;
}];
target
needs to indicate the center of the view: CGPointMake(self.view.center.x, self.view.center.y)
target
需要指示视图的中心: CGPointMake(self.view.center.x, self.view.center.y)
fillMode
removedOnCompletion
autoreverses
repeatCount
to avoid frame changes (final of animation) fillMode
removedOnCompletion
autoreverses
repeatCount
以避免帧更改(动画最终) 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;
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
; 您不是针对正确的目标,而是针对
headerImage
的当前中心; so technically, origin
and target
are the same location here. 因此从技术上讲,
origin
和target
在此处是相同的位置。
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. 您也可以使用
self.view.center.x
,但是它的未来证明要少一些。
Also, I've noticed the keys you're using differ between the two times you use it ("position" and "position.x"). 另外,我注意到您使用的键在两次使用之间有所不同(“ position”和“ position.x”)。 I'm not super comfortable with CAAnimations, so this might be completely right in the first place
我对CAAnimations不太满意,因此一开始这可能完全正确
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.