Ios iPhone-沿触摸和拖动路径移动对象
我正在开发一个简单的动画,Ios iPhone-沿触摸和拖动路径移动对象,ios,objective-c,cocoa-touch,core-animation,iphone-sdk-3.0,Ios,Objective C,Cocoa Touch,Core Animation,Iphone Sdk 3.0,我正在开发一个简单的动画,UIImageView沿着UIBezierPath移动,现在,我想为移动的UIImageView提供用户交互,以便用户可以通过触摸UIImageView来引导UIImageView,并在屏幕上拖动UIImageView。在中更改图像视图位置的帧 编辑:一些代码 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { UITouch *touch = [[event allTouches]
UIImageView
沿着UIBezierPath
移动,现在,我想为移动的UIImageView
提供用户交互,以便用户可以通过触摸UIImageView
来引导UIImageView
,并在屏幕上拖动UIImageView
。在中更改图像视图位置的帧
编辑:一些代码
- (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;
}
您还应该实现
touchesend:withEvent:
和touchecanceled:withEvent:
最简单的方法是子类化UIImageView
对于简单的拖动,请查看此处的代码(从用户MHC借用的代码):
由于要沿贝塞尔路径拖动,因此必须修改触摸移动:
-(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)CalculationPositionForPoint:(CGPoint)location中,您到底想做什么
随你。例如,您可以计算贝塞尔路径中距离位置最近的点。对于简单测试,您可以执行以下操作:
-(CGPoint) calculatePositionForPoint:(CGPoint)location {
return location;
}
在这个过程中,如果用户想离开你的网站很远,你必须决定会发生什么
预先计算的Bezier路径。你想让用户能够在一个关键帧动画中沿着曲线路径触摸一个图像,并把它拖到一个不同的位置吗?此时,您希望动画发生什么变化
你面临多重挑战
首先是在关键帧动画“飞行”时检测对象上的触摸
为此,您需要使用父视图层的表示层的hitTest方法
层的表示层表示层在任何给定时刻的状态,包括动画
一旦检测到视图上的触摸,您将需要从表示层获取图像的当前位置,停止动画,并使用基于触摸移动/触摸拖动的动画接管
我编写了一个演示应用程序,演示如何检测沿路径设置动画的对象上的触摸。这将是一个很好的起点
请看这里:
好的,但是如何识别触摸是否在特定对象上?在该方法中获得的集触摸
中的对象是UITouch,因此它们具有属性视图
,这是触摸最初发生的视图。我尝试了此代码,它正在处理没有任何动画的图像。但是在我的场景中,我沿着贝塞尔路径移动UIImageview,直到动画到达haltSir,移动才发生。我有和你一样的问题,如果你这样做,请帮助我。