2012-03-29 39 views
4

我開發一個簡單的動畫,其中一個UIImageView移動沿着UIBezierPath,現在我想向用戶提供互爲作用到移動UIImageView,使用戶可以通過觸摸UIImageView並拖動引導UIImageView屏幕周圍有UIImageviewiPhone - 移動物體沿觸摸和拖拽路徑

+0

先生,我有同樣的問題,就像你有請幫助我,如果你做那件事。 – 2014-06-11 06:50:07

回答

5

因此,您希望用戶能夠沿着彎曲路徑在關鍵幀動畫的中間觸摸圖像,並將其拖動到其他位置?那時你想要發生什麼動畫?

您有多重挑戰。

首先是在關鍵幀動畫處於「飛行中」時檢測對象上的觸摸。

爲此,您要使用父視圖的圖層的表示層的hitTest方法。

圖層的表示層代表任何給定時刻圖層的狀態,包括動畫。

一旦檢測到視圖上的接觸,您將需要從表示層獲取圖像的當前位置,停止動畫,並接管基於touchesMoved/touchesDragged的動畫。

我寫了一個演示應用程序,演示瞭如何檢測沿路徑動畫的對象的觸摸。這將是一個很好的起點。

到這裏看看:

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

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:

+0

好的,但是如何識別它是否在某個特定的物體上? – Pete 2012-03-29 08:54:35

+0

您在此方法中設置的「touches」中的對象是UITouches,因此它們具有「視圖」屬性,該屬性是最初發生觸摸的視圖。 – dasdom 2012-03-29 09:00:09

+0

您可以分享一小段代碼片段嗎? – Pete 2012-03-29 09:36:33

1

最簡單的方法是繼承UIImageView

對於簡單的拖動來看看這裏的代碼(代碼用戶MHC借來的):

UIView drag (image and text)

既然你想沿着貝塞爾曲線拖你必須修改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; 
} 

除了你要去的方式必須決定是否用戶奇蹟從 預先計算貝塞爾路遠,會發生什麼關來。