在动画期间访问UIView的当前位置

29

我正在尝试找到正在屏幕上动画的iPhone ImageView的当前位置。

我这样创建并对imageView进行动画处理:

-(IBAction)button:(UIButton *)sender{
    UIImageView *myImageView =[[UIImageView alloc] initWithImage:
                                     [UIImage imageNamed:@"ball.png"]];    
    myImageView.frame = CGRectMake(0, self.view.frame.size.height/2, 40, 40);    
    [self.view addSubview:myImageView];
    [myArray addObject:myImageView];

    [UIView animateWithDuration:.5 
                          delay:0 
                options:(UIViewAnimationOptionAllowUserInteraction) // | something here?)
                     animations:^{
                         myImageView.frame = CGRectOffset(myImageView.frame, 500, 0);    
                     }
                     completion:^(BOOL finished){
                         [myArray removeObject:myImageView];
                         [myImageView removeFromSuperview];
                         [myImageView release];
                     }
     ];
}

然后为了检测imageView当前的CGPoint,我每60分之一秒调用一次这个方法。

-(void)findPoint{

    for (UIImageView *projectile in bullets) {        
         label.text = [NSString stringWithFormat:@"%f", projectile.center.x];
         label2.text = [NSString stringWithFormat:@"%f", projectile.center.y];
    }
}

然而,这只给了我动画结束时的点,我想要获取正在跨越屏幕移动的图像的当前CGPoint。除了UIViewAnimationOptionAllowUserInteraction之外,还需要应用其他选项吗?如果没有,那么如何获取正在动画化的imageView的当前位置?

2个回答

53
你可以使用 presentationLayer 属性 - 它是 CALayer 的一个属性,"提供了当前正在显示的图层版本的近似值"。只需像这样使用它:
CGRect projectileFrame = [[projectile.layer presentationLayer] frame];

谢谢!这个完美地运行了,除了一个警告“没有找到'-presentationLayer'方法”。我需要导入一个框架吗? - user975134
足够完美地接受答案了吗? :-) 是的,我忘记提到你应该链接QuartzCore.framework并添加一个导入 #import <QuartzCore/QuartzCore.h>,就像你处理CALayers时一样。 - adamsiton
有没有类似于获取当前变换的东西? - zakdances

3

Swift 5: 使用以下代码获取动画期间的临时位置和大小 (CGRect):

let currentFrame = projectileFrame.layer.presentation()!.frame

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接