layer层

作者: 7dfa9c18c1d1 | 来源:发表于2016-06-03 14:25 被阅读35次
#import "ViewController.h"

@interface ViewController ()
// 这个layer层是渐变色的层
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self testSomeThings];
}

- (void)testSomeThings
{
    // 初始化渐变层
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = self.view.bounds;
    
    // 设置渐变层的颜色
    CGColorRef color1 = [UIColor colorWithWhite:0.5 alpha:0.2].CGColor;
    CGColorRef color2 = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:0.4].CGColor;
    CGColorRef color3 = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.3].CGColor;
    CGColorRef color4 = [UIColor colorWithWhite:0.4 alpha:0.2].CGColor;
    
    self.gradientLayer.colors = [NSArray arrayWithObjects:(__bridge id _Nonnull)(color1), color2, color3, color4, nil];
    self.gradientLayer.locations = @[@0.10, @0.30, @0.50, @0.70, @0.90];
    self.gradientLayer.startPoint = CGPointMake(0, 0); // 范围是0-1
    self.gradientLayer.endPoint = CGPointMake(1, 1);
    
    [self.view.layer addSublayer:self.gradientLayer];
    
    [self shapeLayer];
    
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(randomColor:) userInfo:nil repeats:YES];
}
- (void)randomColor:(NSTimer *)sender
{
    CGFloat redValue = drand48();
    CGFloat blueValue = drand48();
    CGFloat greenValue = drand48();
    self.view.backgroundColor = [UIColor colorWithRed:redValue green:greenValue blue:blueValue alpha:1.0];
}
- (void)shapeLayer
{
    // 画图的layer层
    CAShapeLayer *layer = [CAShapeLayer layer];
    
    // 创建路径
    CGMutablePathRef path = CGPathCreateMutable();
    
    // 设置起点(path:给哪个路径设置起点)
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    // 加载一条线到某个点
    CGPathAddLineToPoint(path, NULL, self.view.bounds.size.width, self.view.bounds.size.height);
    
    layer.path = path;
    
    layer.fillColor = [UIColor whiteColor].CGColor;
    
    layer.strokeColor = [UIColor redColor].CGColor;
    
    layer.strokeEnd = 1;
    
    [self.view.layer addSublayer:layer];
    
    // 给layer层添加动画
    CABasicAnimation *anim = [CABasicAnimation animation];
    anim.keyPath = @"strokeEnd";
    anim.fromValue = @0;
    anim.toValue = @1;
    anim.duration = 5;
    [layer addAnimation:anim forKey:nil];
    
    [self.view setNeedsDisplay];
}

相关文章

网友评论

      本文标题:layer层

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