CAShapLayer的使用1
1.添加橙色圆环
- (CAShapeLayer *)shapeLayer { if (!_shapeLayer) { _shapeLayer = [CAShapeLayer layer]; CGRect rect = {28,50,100,100}; //bezierPathWithOvalInRect圆形路径 bezierPathWithRect 方形路径 UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect: rect]; _shapeLayer.strokeColor = [UIColor orangeColor].CGColor; _shapeLayer.lineWidth = 4; _shapeLayer.fillColor = [UIColor clearColor].CGColor; _shapeLayer.lineCap = kCALineCapRound; _shapeLayer.path = path.CGPath; } return _shapeLayer; }
2.添加进度条
- (CAShapeLayer *)progressLayer { if (!_progressLayer) { _progressLayer = [CAShapeLayer layer]; _progressLayer.frame = self.shapeLayer.bounds; _progressLayer.fillColor = [UIColor clearColor].CGColor; _progressLayer.strokeColor = [UIColor whiteColor].CGColor; _progressLayer.lineWidth = 4; _progressLayer.lineCap = kCALineCapRound; CGRect rect = {28,50,100,100}; UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect: rect]; _progressLayer.path = path.CGPath; } return _progressLayer; }
3.添加渐变颜色
[self.view.layer addSublayer: self.shapeLayer]; [self.view.layer addSublayer: self.progressLayer]; CAGradientLayer * gradientLayer1 = [CAGradientLayer layer]; gradientLayer1.frame = self.view.bounds; CGColorRef red = [UIColor redColor].CGColor; CGColorRef purple = [UIColor purpleColor].CGColor; CGColorRef yellow = [UIColor yellowColor].CGColor; CGColorRef orange = [UIColor orangeColor].CGColor; gradientLayer1.colors = @[(__bridge id)red,(__bridge id)purple,(__bridge id)yellow,(__bridge id)orange]; gradientLayer1.locations = @[@0.3, @0.6,@0.8,@1.0]; gradientLayer1.startPoint = CGPointMake(0.5, 1); gradientLayer1.endPoint = CGPointMake(0.5, 0); //一定要设置gradientLayer.mask = self.progressLayer;这样才能显示中间的内容,如果不设置mask,那么就只有渐变图层了 gradientLayer1.mask = self.progressLayer; [self.view.layer addSublayer: gradientLayer1]; //添加渐变
4.执行动画
- (IBAction)change:(UISlider * )sender { CGFloat cV = sender.value * 100; [self updateProgressWithNumber: cV]; } - (void)updateProgressWithNumber:(NSUInteger)number { [CATransaction begin]; [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; [CATransaction setAnimationDuration:0.5]; self.progressLayer.strokeEnd = number / 100.0; NSLog(@"%@",[NSString stringWithFormat:@"%@%%", @(number)]); [CATransaction commit]; }