iPhone - 沿触摸和拖动路径移动对象

时间:2012-03-29 08:10:58

标签: ios objective-c cocoa-touch core-animation iphone-sdk-3.0

我正在开发一个简单的动画,其中UIImageView沿着UIBezierPath移动,现在我想为移动的UIImageView提供用户交互,以便用户可以引导UIImageView触摸UIImageView并在屏幕上拖动UIImageview

3 个答案:

答案 0 :(得分:9)

touchesMoved:withEvent:中更改图像视图位置的框架。

编辑:一些代码

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [[event allTouches] anyObject];
    if ([touch.view isEqual: self.view] || touch.view == nil) {
        return;
    }

    lastLocation = [touch locationInView: self.view];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [[event allTouches] anyObject];
    if ([touch.view isEqual: self.view]) {
        return;
    }

    CGPoint location = [touch locationInView: self.view];

    CGFloat xDisplacement = location.x - lastLocation.x;
    CGFloat yDisplacement = location.y - lastLocation.y;

    CGRect frame = touch.view.frame;
    frame.origin.x += xDisplacement;
    frame.origin.y += yDisplacement;
    touch.view.frame = frame;
    lastLocation=location;
}

您还应该实施touchesEnded:withEvent:touchesCanceled:withEvent:

答案 1 :(得分:5)

因此,您希望用户能够沿着弯曲路径触摸关键帧动画中间的图像,并将其拖动到其他位置?你想在那时发生什么动画?

您有多重挑战。

首先是在关键帧动画“飞行中”时检测物体上的触摸。

为此,您需要使用父视图的图层表示层的hitTest方法。

图层的表示层表示任何给定时刻图层的状态,包括动画。

一旦检测到视图上的触摸,您将需要从表示层获取图像的当前位置,停止动画,并使用基于touchesMoved / touchesDragged的动画接管。

我编写了一个演示应用程序,演示如何检测沿路径动画的对象上的触摸。那将是一个很好的起点。

看看这里:

Core Animation demo including detecting touches on a view while an animation is "in flight".

答案 2 :(得分:1)

最简单的方法是继承UIImageView

对于简单的拖动,请查看此处的代码(从用户MHC借来的代码):

UIView drag (image and text)

由于您要沿Bezier路径拖动,因此您必须修改touchesMoved:

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

        UITouch *aTouch = [touches anyObject];

        //here you have location of user's finger
        CGPoint location = [aTouch locationInView:self.superview];

        [UIView beginAnimations:@"Dragging A DraggableView" context:nil];

        //commented code would simply move the view to that point  
        //self.frame = CGRectMake(location.x-offset.x,location.y-offset.y,self.frame.size.width, self.frame.size.height);

        //you need some kind of a function
        CGPoint calculatedPosition = [self calculatePositonForPoint: location];

        self.frame = CGRectMake(calculatedPosition.x,calculatedPosition.y,self.frame.size.width, self.frame.size.height);

        [UIView commitAnimations];
    }

你想在-(CGPoint) calculatePositionForPoint:(CGPoint)location做什么 你决定。例如,您可以计算最接近location的Bezier路径中的点。对于简单测试,您可以这样做:

-(CGPoint) calculatePositionForPoint:(CGPoint)location {

    return location;
}

一路上你将不得不决定如果用户想知道远离你的情况会发生什么 预先计算的Bezier路径。