【问题标题】:How can I touch and drag an animated image? here's my animation code:如何触摸和拖动动画图像?这是我的动画代码:
【发布时间】:2012-04-14 09:48:13
【问题描述】:
- (void)viewDidLoad
{
    [super viewDidLoad];


        [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:4];
    [UIView setAnimationRepeatCount:50];
    [UIView setAnimationRepeatAutoreverses:NO];

    CGPoint abc =chem1.center;

    abc.y= 480;
    chem1.center=abc; 

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:4];
    [UIView setAnimationRepeatCount:50];
    [UIView setAnimationRepeatAutoreverses:NO];

    CGPoint def =chem2.center;

    def.y= 480 ;
    chem2.center=def; 

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:4];
    [UIView setAnimationRepeatCount:50];
    [UIView setAnimationRepeatAutoreverses:NO];

    CGPoint hij =nat1.center;

    hij.y= 480;
    nat1.center=hij; 

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:4];
    [UIView setAnimationRepeatCount:50];
    [UIView setAnimationRepeatAutoreverses:NO];

    CGPoint klm =nat2.center;

    klm.y= 480;
    nat2.center=klm;  
}

非常感谢您的帮助

【问题讨论】:

    标签: objective-c ios animation drag-and-drop


    【解决方案1】:

    您的问题分为两部分:如何点按动画图像和如何拖动图像。


    如何点按动画图像。

    背景

    当您为视图(或更准确地说是其层)设置动画时,您更改的属性(在您的情况下为position(通过设置center))会立即更改为其最终值。如果您只制作动画(例如使用 CABasicAnimation,那么正确的可能根本不会改变。

    这意味着如果您尝试点击视图(或图层),它将位于您将其移动到的位置(其最终位置(尽管动画的任何持续时间或重复次数)。

    点击测试移动层

    为了能够对正在移动的东西进行测试,您需要针对您尝试点击的视图层的presentationLayer 进行测试。

    CGPoint touchPoint = [gestureRecognizer locationInView:[self view]];
    
    if ([[[[self movingView] layer] presentationLayer] hitTest:touchPoint]) {
        // Yeah, you hit the moving (animating) layer!
    }
    

    现在用户已经点击了一个移动视图(在你的例子中是图像),你可以开始处理拖动了。

    如何拖动图片

    当您拖动图像时,您会将图层移动到用户手指拖动图像的任何位置。

    移除到移动视图的动画

    首先,您应该取消该视图正在进行的动画(拥有动画名称可以让您只取消一个动画。

    [[[self movingView] layer] removeAllAnimations];
    

    或者,如果您为移动动画设置了名称。

    [[[self movingView] layer] removeAnimationForKey:@"nameOfMovingAnimation"];
    

    将视图移动到用户手指的位置

    接下来,您应该(持续)在用户移动手指时更新视图的位置。您不应该对此进行动画处理,因为它会增加手指移动和视图之间的时间,并使您的应用程序看起来像是滞后的。 在拖动时动画不会使它看起来平滑。

    注意:因为您的问题并未说明用户拖动图像后您想要做什么,或者当他们放下图像时会发生什么。我无法进一步解释。

    需要更多帮助?

    在网络(或 StackOverflow)上搜索类似“iOS 拖动视图”的内容,您可能会找到有关如何拖动 imageView 的更多信息。

    否则,一旦你走到这一步,就在 StackOverflow 上再问一个问题(即你可以点击移动的图像,它们就会停止移动)。

    【讨论】:

    • 所以无法在动画图像上启用用户交互?
    • 是的。您只需点击测试表示层即可知道用户何时点击图像,然后使用您的标准代码拖动它
    • 我已经用更详细的解释更新了我的答案。这是否有助于您了解如何实现这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多