Accessing the current position of UIView during animation
Asked Answered
F

2

29

I am trying to find the current position of an iPhone ImageView that is animating across the screen.

I create and animate the imageView like so

-(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];
                     }
     ];
}

then to detect the current CGPoint of the imageView I call this method every 60th of a second

-(void)findPoint{

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

However this only gives me the point where the animation ends, I want to get the current CGPoint of the image that is animating across the screen. Is there an option that I need to apply other than UIViewAnimationOptionAllowUserInteraction to do this? If not, how do I get the current position of an animating imageView?

Flaunt answered 2/10, 2011 at 5:20 Comment(0)
S
54

You can use the presentationLayer - a property of the CALayer that "provides a close approximation to the version of the layer that is currently being displayed". Just use it like this:

CGRect projectileFrame = [[projectile.layer presentationLayer] frame];
Steepen answered 2/10, 2011 at 8:30 Comment(3)
Thank you!! this works perfectly, other than a warning no '-presentationLayer' method found. Do I have to import a framework?Flaunt
perfectly enough to accept the answer? :-) Yes, i forgot to mention that you should link QuartzCore.framework and add an import #import <QuartzCore/QuartzCore.h>, like you would whenever you deal with CALayers.Steepen
Is there something similar to get the current transform?Rolf
P
4

Swift 5: Get temporary position and size (CGRect) during the animation with:

let currentFrame = projectileFrame.layer.presentation()!.frame
Peshawar answered 2/11, 2019 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.