2014-07-23 36 views
0

我想要將圖像動畫到持續12秒的UIBezier路徑上。我正在使用CAKeyframeAnimation。我的問題是,我想從起點到第一點,從第一點到第二點4秒,從第二點到第三點4秒,從第三點到終點2秒,爲圖像製作動畫2秒。我怎樣才能做到這一點?這是我的代碼。CAKeyFrameAnimation在特定的UIBezierPath上具有不同的持續時間?

CGPoint startingpoint = CGPointMake(self.bounds.origin.x + 98, self.bounds.size.height -20); 
CGPoint firstPoint = CGPointMake(startingpoint.x + 20,startingpoint.y); 
CGPoint secondpoint = CGPointMake(firstPoint.x + 30,firstPoint.y - 80); 
CGPoint thirdpoint = CGPointMake(secondpoint.x + 50, secondpoint.y + 80); 
CGPoint endPoints = CGPointMake(thirdpoint.x + 20,thirdpoint.y); 

UIBezierPath *path = [UIBezierPath bezierPath]; 
[path moveToPoint:startingpoint]; 
[path addLineToPoint:firstPoint]; 
[path addLineToPoint:secondpoint]; 
[path addLineToPoint:thirdpoint]; 
[path addLineToPoint:endPoints]; 

CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 
shapeLayer.path = [path CGPath]; 
shapeLayer.strokeColor = [[UIColor whiteColor] CGColor]; 
shapeLayer.lineWidth = 3.0; 
shapeLayer.fillColor = [[UIColor clearColor] CGColor]; 
[self.layer addSublayer:shapeLayer]; 

CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 
animation1.duration = 10; 
animation1.path = path.CGPath; 
animation1.autoreverses = NO; 
animation1.repeatCount = 0; 
[myImageView.layer addAnimation:animation1 forKey:@"position"]; 

回答

1

您在動畫中缺少一些東西。具體而言,您並未在CAKeyframeAnimation上設置任何keyTimes或值。儘管它們是可選的,但核心動畫並不知道您希望在2秒後更改值,然後在4秒後再更改一次。你必須告訴動畫你想要什麼。

要做到這一點,你需要兩個等長的NSArray s。第一個將有你的關鍵幀的時間作爲動畫的總時間一個因素:

CFTimeInterval d = 12.0f; // 12 seconds total time 
NSArray * keyTimes = @[@(0), @(2/d), @(6/d), @(10/d), @(1.0)]; 

和其他將是值的列表(在包裹在NSValues這種情況下CGPoint因爲你動畫一個CGPoint類型的屬性)到那些keyTimes將對應:

NSArray * pointValues = @[[NSValue valueWithCGPoint:startingPoint], [NSValue valueWithCGPoint:firstPoint], [NSValue valueWithCGPoint:secondPoint], [NSValue valueWithCGPoint:thirdPoint], [NSValue valueWithCGPoint:endPoint]]; 

最後把它們放在動畫:

animation1.keyTimes = keyTimes; 
animation1.values = values; 

如果你想獲得真正看中的,你還可以指定計時功能所提供的密鑰時間之間的每個值變化的時刻的N-1長數組:

CAMediaTimingFunction * linear = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
CAMediaTimingFunction * easeIn = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 
CAMediaTimingFunction * fastEaseInOut = [CAMediaTimingFunction functionWithControlPoints:0.30f :0.92f :0.86f :0.95f]; 

NSArray * timingFunctions = @[easeIn, linear, linear, fastEaseInOut]; 
animation1.timingFunctions = timingFunctions; 
相關問題