【问题标题】:Animate a UIImageView in the middle of an animation在动画中间为 UIImageView 设置动画
【发布时间】:2012-09-23 23:07:25
【问题描述】:

我有一个物体在屏幕上从右向左移动:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:7.8];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
 myImageview.layer.position = CGPointMake(20,  myImageView.layer.position.y);
[UIView commitAnimations];

我发现即使动画仍在播放,XCode 已经将图像的位置标记为其最终目的地,为了检测移动图像上的触摸,我需要使用presentationLayer:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];

    if ([myImageview.layer.presentationLayer hitTest:touchPoint]) {
        NSLog(@"it's a hit!");
    }
}

这部分有效。 现在,我希望图像在按下时向上移动。 我希望图像在继续横向移动的同时向上移动。 相反,这段代码不仅将图像向上移动,而且一直移动到左侧的最终目的地:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];   
    CGPoint touchPoint = [touch locationInView:self.view];

    if ([mouse.layer.presentationLayer hitTest:touchPoint]) {
        NSLog(@"it's a hit!");
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        myImageView.layer.position = CGPointMake( mouse.layer.position.x,  myImageView.layer.position.y - 40);
        [UIView commitAnimations];
    }
}

我希望图像在继续横向移动的同时向上移动。 有谁知道实现这一点的方法吗?

非常感谢!

【问题讨论】:

    标签: iphone animation uiimageview presentation-layer


    【解决方案1】:

    您是否尝试过设置动画选项UIViewAnimationOptionBeginFromCurrentState

    (我之所以说选项,是因为它是 iOS 4 引入的基于块的动画方法中的一个选项。如果您还不能切换到已弃用的 UIView 类方法,它也可以作为 [UIView setAnimationBeginsFromCurrentState:YES] 使用。)

    touchesBegan 变为(使用块动画):

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        [super touchesBegan:touches withEvent:event];
    
        UITouch *touch = [touches anyObject];   
        CGPoint touchPoint = [touch locationInView:self.view];
    
        if ([mouse.layer.presentationLayer hitTest:touchPoint]) {
            NSLog(@"it's a hit!");
            [UIView animateWithDuration:0.5 delay:0.0 options:(UIViewAnimationOptionCurveLinear & UIViewAnimationOptionBeginFromCurrentState) animations:^{
                myImageView.layer.position = CGPointMake( myImageView.layer.position.x,  mouse.layer.position.y - 40);
            }completion:^(BOOL complete){
                //
            }];
        }
    }
    

    如果您使用它,您应该能够指定您想要的最终xy 坐标,并让动画从对象被触摸的点继续到该位置。

    【讨论】:

    • 太棒了!这是一个我完全不知道的好选择!
    • 很有趣,它取代了之前的动画。我试图让原始动画继续,因为它只影响 x 轴并沿途将动画添加到 y 轴。这绝对是一个有趣的选项,但仍然无法按原样工作,因为它不仅将我的 imageView 向上移动,而且还将其发送到左侧的最终目的地。非常感谢!将使用这个新选项。 =)
    • 您确实需要重新计算和更改动画参数以获得您想要的最终结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2011-06-13
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多