iPhone – 沿着触摸和拖动path移动对象

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

因此,您希望用户能够沿着弯曲的path在关键帧animation的中间触摸图像,并将其拖动到不同的位置? 那个时候你想要发生什么animation呢?

你有多个挑战。

首先是在关键帧animation“在飞行中”时检测对象上的触摸。

要做到这一点,你想使用父视图的图层的表示层的hitTest方法。

一个图层的表示层代表在任何给定时刻图层的状态,包括animation。

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

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

看看这里:

核心animation演示包括在animation“飞行中”时检测视图上的触摸。

在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:

最简单的方法是UIImageView

对于简单的拖动看看这里的代码(从用户MHC借来的代码):

UIView拖动(图像和文字)

既然你想要沿贝塞尔path拖动,你将不得不修改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 Bezierpath中的location 。 对于简单的testing,你可以做:

 -(CGPoint) calculatePositionForPoint:(CGPoint)location { return location; } 

一路上,你将不得不决定如果用户想要远离预先计算的贝塞尔path会发生什么情况。