是否可以为CGContextDrawPath设置动画

时间:2015-11-10 11:27:49

标签: ios core-graphics

[0,0] [0,1] 1 1 
[0,2] [0,3] 1 1
   2     2  3 3
   2     2  3 3

使用CGContextDrawPath绘制形状时,是否可以从头到尾为路径设置动画?

2 个答案:

答案 0 :(得分:1)

你可能不需要在drawRect中这样做,而是在一个自定义的setupView函数中,从viewDidAppear:(BOOL)调用动画。

- (void) setupView {
self.graphLayer = [[CAShapeLayer alloc] init];
self.graphLayer.strokeColor = [UIColor redColor].CGColor;  // GRAPH_LINE_COLOR.CGColor
self.graphLayer.fillColor = [UIColor clearColor].CGColor;
[self.layer addSublayer:self.graphLayer];

[self animateContour];

}

animateContour从开始到结束动画

-(void) animateContour {
CGFloat SCREEN_WIDTH = [UIScreen mainScreen].bounds.size.width;  // your values here
CGFloat SCREEN_HEIGHT = [UIScreen mainScreen].bounds.size.height;

UIBezierPath* path0 = [UIBezierPath bezierPath];
[path0 moveToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];
[path0 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];

UIBezierPath* path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];
[path1 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95,SCREEN_HEIGHT * 0.20)];

UIBezierPath* path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];
[path2 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95,SCREEN_HEIGHT * 0.20)];
[path2 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95, SCREEN_HEIGHT * 0.85)];

UIBezierPath* path3 = [UIBezierPath bezierPath];
[path3 moveToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];
[path3 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95,SCREEN_HEIGHT * 0.20)];
[path3 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95, SCREEN_HEIGHT * 0.85)];
[path3 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.85)];

UIBezierPath* path4 = [UIBezierPath bezierPath];
[path4 moveToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];
[path4 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95,SCREEN_HEIGHT * 0.20)];
[path4 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.95, SCREEN_HEIGHT * 0.85)];
[path4 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.85)];
[path4 addLineToPoint:CGPointMake(SCREEN_WIDTH * 0.10, SCREEN_HEIGHT * 0.20)];

CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"path"];
animation.duration = 4.0f;
animation.values = [NSArray arrayWithObjects:(id)path0.CGPath, (id)path1.CGPath,
                    (id)path2.CGPath, (id)path3.CGPath,
                    (id)path4.CGPath, nil];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = false;
[self.graphLayer addAnimation:animation forKey:@"path"];

}

答案 1 :(得分:0)

动画最好在-drawRect:之外完成,改为使用CAShapeLayer

questions/10809280