美文网首页
不借助第三方库UIBezierPath+CAShapeLayer

不借助第三方库UIBezierPath+CAShapeLayer

作者: 蛮大人_3b6c | 来源:发表于2018-04-25 14:20 被阅读0次

实现思路:

UIBezierPath勾勒轮廓,CAShapeLayer按照轮廓画出形状,CAGradientLayer做颜色渐变,让CAShapeLayer做CAGradientLayer的遮罩mask, 

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) CAShapeLayer *shapLayer;

@property (nonatomic,strong) CAGradientLayer *gradientLayer;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    [self.gradientLayer setMask:self.shapLayer];

    [self.view.layer addSublayer:self.gradientLayer];

    [self drawCircleAnimation:self.shapLayer];

}

- (CAShapeLayer*)shapLayer{

    if(_shapLayer==nil) {

        CGSize size = self.view.bounds.size;

        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(size.width/2, size.height/2) radius:size.width/2 - 1 startAngle:M_PI endAngle:M_PI * 2 clockwise:YES];

        _shapLayer= [CAShapeLayerlayer];

        _shapLayer.path= path.CGPath;

        _shapLayer.fillColor= [[UIColorclearColor]CGColor];

        _shapLayer.strokeColor= [[UIColorredColor]CGColor];

        _shapLayer.lineWidth=1;

        _shapLayer.lineCap = kCALineCapRound;

    }

    return _shapLayer;

}

- (CAGradientLayer*)gradientLayer{

    if (_gradientLayer == nil) {

        CGSize size = self.view.bounds.size;

        _gradientLayer = [CAGradientLayer layer];

        _gradientLayer.frame=CGRectMake(0,0, size.width, size.width);

        _gradientLayer.backgroundColor = [[UIColor grayColor] CGColor];

        _gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,

                                  (__bridgeid)[UIColorgreenColor].CGColor,

                                  (__bridgeid)[UIColoryellowColor].CGColor,

                                  (__bridgeid)[UIColorblueColor].CGColor];

        _gradientLayer.locations  =@[@(0.2), @(0.4), @(0.6),@(0.8)];

        _gradientLayer.startPoint=CGPointMake(0,0);

        _gradientLayer.endPoint=CGPointMake(1,0);

    }

    return _gradientLayer;

}

- (void)drawCircleAnimation:(CALayer*)lay

{

    CABasicAnimation *baseAnimation=[CABasicAnimation animationWithKeyPath:@"strokeEnd"];

    baseAnimation.duration=5.0;

    baseAnimation.fromValue=[NSNumber numberWithInteger:0];

    baseAnimation.toValue=[NSNumber numberWithInteger:1.0];

    [layaddAnimation:baseAnimation forKey:@"circleKey"];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

相关文章

网友评论

      本文标题:不借助第三方库UIBezierPath+CAShapeLayer

      本文链接:https://www.haomeiwen.com/subject/zixylftx.html