2013-02-11 45 views
0

我的第一個Core Animation只是一個從a點移動到b的圖像。出於某種原因,當動畫被調用時,會出現一個紅框,並在它坐落在那裏時移動到我的圖像位置。 這裏是我的代碼:Red Box在Core Animation中移動UIImage視圖

-(IBAction)preform:(id)sender{ 
CALayer *layer = [CALayer layer]; 
[layer setPosition:CGPointMake(100.0, 100.0)]; 
[layer setBounds:CGRectMake(0.0, 0.0, 50.0, 60.0)]; 
[layer setBackgroundColor:[[UIColor redColor] CGColor]]; 
[imView.layer addSublayer:layer]; 

CGPoint point = CGPointMake(imView.frame.origin.x, imView.frame.origin.y); 
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"]; 
anim.fromValue = [NSValue valueWithCGPoint:point]; 
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)]; 
anim.duration = 1.5f; 
anim.repeatCount =1; 
anim.removedOnCompletion = YES; 
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 
[layer addAnimation:anim forKey:@"position"]; 
} 
+0

乘坐一會兒再讀一遍你的代碼。它正在做你正在問的問題。爲什麼你首先要創建紅色圖層? – 2013-02-11 02:52:44

回答

1

如果您不需要爲您的應用程序的用戶界面,紅盒子,不要創建它,而是將動畫應用於視圖的層。如果你需要一個紅色的框,確實創造,但動畫應用到視圖的層,而不是紅色框層

還要注意的是,除非你改變你的層的anchorPoint,該position屬性實際上是層的中心,不是角落。您需要考慮製作流暢的動畫。

最後,如果您不希望視圖在動畫完成後回彈,則需要將其設置爲新位置。別擔心,在動畫播放過程中,視圖的重定位不可見。

建議(和未經測試)代碼:

-(IBAction)preform:(id)sender{ 

    CGPoint point = CGPointMake(imView.frame.size.width/2.0 , imView.frame.size.height/2.0); 
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"]; 
    anim.fromValue = [NSValue valueWithCGPoint:point]; 
    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)]; 
    anim.duration = 1.5f; 
    anim.repeatCount =1; 
    anim.removedOnCompletion = YES; 
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 
    [imView.layer addAnimation:anim forKey:@"position"]; 

    imView.center = CGPointMake(imView.center.x + 50, imView.center.y 
} 

這都將是更容易,如果你使用的UIView動畫輔助功能,而不是,但我想你正在努力學習如何使用CAAnimation

+0

我知道UIView動畫很好,我試圖做更復雜的動畫,所以我搬到了CA.謝謝您的幫助! – Tanner 2013-02-11 03:25:23

相關問題