将UIImageView从左移动到中心

时间:2016-07-22 14:31:23

标签: ios objective-c

我想将图像视图从左侧移动到视图的中心。

以下是我的代码:

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

加载视图控制器时,必须从左侧开始移动并在中心停止。但它不能正常工作。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

使用

[UIView animateWithDuration:1.0 animations:^{
    headerImage.frame = myNewFrameRect;
}];

答案 1 :(得分:2)

  1. target需要指明视图的中心:CGPointMake(self.view.center.x, self.view.center.y)
  2. 更改fillMode removedOnCompletion autoreverses repeatCount以避免更改框架(动画结束)
  3. 最终代码:

    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;
    

答案 2 :(得分:2)

问题在于:

CGPoint origin = self.headerImage.center;
CGPoint target = CGPointMake(0, self.headerImage.center.x);

你并非瞄准正确的目标,而是瞄准headerImage的当前中心;从技术上讲,origintarget在这里是相同的位置。

将目标移动到超级视图的中心,你会很好:)

CGPoint target = CGPointMake(0, self.headerImage.superView.center.x);

您也可以使用self.view.center.x,但未来的证据稍微少一些。

另外,我注意到你使用的两个键在你使用它的两次(“position”和“position.x”)之间有所不同。我对CAAnimations不太满意,所以这可能在第一时间完全正确