2013-07-15 87 views
0

我是使用Quartz2D的新手,並且從小開始我想繪製一條線,但是從頭到尾都要對該線進行動畫處理。從我看過的博客和我看過的類似問題看來,我似乎需要爲圖層設置路徑,並在該圖層上設置動畫。對我來說問題是,即使圖層具有路徑屬性,但我不確定如何正確設置路徑。使用Quart2D動畫路徑的過程

我有一個UIView顯示,它顯示一條線就好了,如果我註釋掉動畫代碼。

CGContextRef context = UIGraphicsGetCurrentContext(); 

CGContextSetLineWidth(context, 2.0); 

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); 

CGFloat components[] = {0.0, 0.0, 1.0, 1.0}; 

CGColorRef color = CGColorCreate(colorspace, components); 

CGContextSetStrokeColorWithColor(context, color); 

CGContextMoveToPoint(context, 0, 0); 
CGContextAddLineToPoint(context, 300, 400); 

CGContextStrokePath(context); 
CGColorSpaceRelease(colorspace); 
CGColorRelease(color); 

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 
pathAnimation.duration = 10.0; 
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; 
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f]; 
//[aLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"]; 

我需要做些什麼來動畫從頭到尾的一條線?

回答

0

這是我用過的動畫被劃的線,一定要導入課程的石英:

//Create the bezier path that will hold all the points of data 
UIBezierPath* bezierPath = [UIBezierPath bezierPath]; 
[[UIColor greenColor] setFill]; 
[bezierPath fill]; 
[[UIColor redColor] setStroke]; 
[bezierPath stroke]; 

for (int i = 10 ; i < 20; i++) { 
    //If its the first point we need to make sure and move to that point not add to it 
    if (i == 10) 
     [bezierPath moveToPoint: CGPointMake(10, 10)]; 
    else 
     [bezierPath addLineToPoint: CGPointMake(i * 2, i * 3)]; 
} 


CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 
shapeLayer.strokeColor = [[UIColor blueColor] CGColor]; 
shapeLayer.fillColor = nil; 
shapeLayer.lineWidth = 10.0f; 
shapeLayer.lineJoin = kCALineJoinRound; 
shapeLayer.path = bezierPath.CGPath; 

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 
pathAnimation.duration = 10.0; 
pathAnimation.fromValue = @(0.0f); 
pathAnimation.toValue = @(1.0f); 

[shapeLayer addAnimation:pathAnimation forKey:@"strokeEnd"]; 

[self.view.layer addSublayer:shapeLayer]; 
+0

真棒,正是我需要的。找不到像這樣的完整解決方案,只有動畫部分。謝謝 –

+0

很高興我可以幫助:) – random