简体   繁体   中英

Changing position during animation?

I have an UIImageView with the size of 64x64 . I want to animate its size down to 8x8. It works fine. However when i change position of point1 (touchPositionInView) from outside the animation it won't update and it will instead animate from the original position where the touches began. Is there any way to fix this?

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView beginAnimations:@"widen" context:nil];
    [UIView setAnimationDuration:1.0];
    CGRect newRect = yellow.frame;
    newRect.size.height = 8;
    newRect.size.width = 8;
    yellow.center = point1;
    yellow.frame = newRect;
    [UIView commitAnimations];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    point1 = [touch locationInView:View];
}

Use the UIView 's animateWithDuration:delay:options:animations:completion: method and provide UIViewAnimationOptionBeginFromCurrentState and UIViewAnimationOptionAllowAnimatedContent in options.

Source:

UIView Class Reference

your problem is that touchesBegan:withEvent: is only called once and touchesMoved:withEvent: is called on every movement.

I suggest you add an animation block in your touchesMoved:withEvent: method also. :-)

Store the point1 and resize your image to 8, 8 and start position animation.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    point1 = [touch locationInView:View];

    [UIView beginAnimations:@"widen" context:nil];
    [UIView setAnimationDuration:1.0];
    CGRect newRect = yellow.frame;
    newRect.size = CGSizeMake(8, 8);
    yellow.frame = newRect;
    [self updatePoint:NO];
    [UIView commitAnimations];
}

Update the position on every move and start the position animation.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    point1 = [touch locationInView:View];
    [self updatePoint:YES];
}

Do the position animation.

- (void)updatePoint:(BOOL)animated
{

    // I think it would be an approvement, if you calculate the duration by the distance from the
    // current point to the target point
    if (animated)
    {
        yellow.center = point1;
    }
    else
    {
        [UIView animateWithDuration:1.0
                              delay:0
                            options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowAnimatedContent
                         animations:^{
                             yellow.center = point1;
                         }
                         completion:^(BOOL finished){}
        ];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM