2012-09-06 106 views
11

我試圖做一個動畫,我將一個CGPoint從一個視圖移動到另一個視圖,我想找到點的座標將參考首先,我可以做動畫。將CGPoint從一個視圖轉換爲另一個視圖相對於動畫

所以我們假設我在view2中有一個點(24,15),並且我想將它設爲view1的動畫,我仍然想要在新視圖中保留點的值,因爲我添加了點作爲新視圖的子視圖,但對於動畫我需要知道點的位置的價值,所以我可以做一個補間。

請參考此圖:

enter image description here

現在,這是我想要做的事:

customObject *lastAction = [undoStack pop]; 
customDotView *aDot = lastAction.dot; 
CGPoint oldPoint = aDot.center; 
CGPoint newPoint = lastAction.point; 

newPoint = [lastAction.view convertPoint:newPoint toView:aDot.superview]; 


CABasicAnimation *anim4 = [CABasicAnimation animationWithKeyPath:@"position"]; 
anim4.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
anim4.fromValue = [NSValue valueWithCGPoint:CGPointMake(oldPoint.x, oldPoint.y)]; 
anim4.toValue = [NSValue valueWithCGPoint:CGPointMake(newPoint.x, newPoint.y)]; 
anim4.repeatCount = 0; 
anim4.duration = 0.1; 
[aDot.layer addAnimation:anim4 forKey:@"position"]; 


[aDot removeFromSuperview]; 


[lastAction.view addSubview:aDot]; 
[lastAction.view bringSubviewToFront:aDot]; 

aDot.center = newPoint; 

任何想法?

+0

這兩個視圖都可以顯示嗎?它們是否包含在更大的視圖中? –

回答

8

用塊動畫更容易看到。我認爲目標是在座標空間中執行view2子視圖的動畫,然後當動畫完成時,使用轉換爲新座標空間的結束位置向view1添加子視圖。

// assume we have a subview of view2 called UIView *dot; 
// assume we want to move it by some vector relative to it's initial position 
// call that CGPoint offset; 

// compute the end point in view2 coords, that's where we'll do the animation 
CGPoint endPointV2 = CGPointMake(dot.center.x + offset.x, dot.center.y + offset.y); 

// compute the end point in view1 coords, that's where we'll want to add it in view1 
CGPoint endPointV1 = [view2 convertPoint:endPointV2 toView:view1]; 

[UIView animateWithDuration:1.0 animations:^{ 
    dot.center = endPointV2; 
} completion:^(BOOL finished) { 
    dot.center = endPointV1; 
    [view1 addSubview:dot]; 
}]; 

請注意,將點添加到view1會將其從view2中刪除。還要注意,如果view1應該有clipsToBounds == NO如果偏移向量移動它的邊界外的點。

相關問題