Dynamically draw curves on iOS
A function needs to be completed recently, that is, to dynamically draw a curve on the screen. This curve can be used to describe the changes of data within a certain period of time. This is probably the following effect.
How can this effect be achieved? These three classes are required: UIBezierPath CAShapeLayer and CABasicAnimation. UIBezierPath is used to draw the corresponding curve Path, CAShapeLayer is used to provide the display position for the Path, and add the animation created by CABasicAnimation to the Path.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + Environment + c + Environment/environment = "brush: java;"> UIBezierPath * path = [UIBezierPath bezierPath]; [path moveToPoint: CGPointMake (0.0, 20.0)]; [path addLineToPoint: CGPointMake (120.0, 500.0)]; [path addLineToPoint: CGPointMake (220, 0)]; [path addLineToPoint: CGPointMake (310, 40)]; [path addLineToPoint: CGPointMake (SCREEN_WIDTH, 110)];
Then we create our own attributes for CAShapeLayer and assign our path to it. Without this assignment, the layer won't be able to draw this effect for us, and it is also an incomplete layer.
CAShapeLayer *pathLayer = [CAShapeLayer layer]; pathLayer.frame = self.view.bounds; pathLayer.path = path.CGPath; pathLayer.strokeColor = [[UIColor redColor] CGColor]; pathLayer.fillColor = nil; pathLayer.lineWidth = 2.0f; pathLayer.lineJoin = kCALineJoinBevel; [self.view.layer addSublayer:pathLayer];
Finally, we assign the animation to our layer. In our animation effect, we can change some of the parameters to control its painting effect.
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; pathAnimation.duration = 2.0; pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; pathAnimation.toValue = [NSNumber numberWithFloat:1.0f]; [pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
Now we can run the code to get the effect in the previous image ~