1. 程式人生 > >CALayer mask 遮罩

CALayer mask 遮罩

mask - 遮罩,遮罩之外部分不會顯示

CAGradientLayer - 漸變色layer


UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(5, 5)];
    [path addLineToPoint:CGPointMake(80, 5)];
    [path addLineToPoint:CGPointMake(100, 30)];
    [path addLineToPoint:CGPointMake(120, 5)];
    [path addLineToPoint:CGPointMake(140, 80)];
    [path closePath];
    
    //遮罩layer
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = [UIColor purpleColor].CGColor;
    shapeLayer.fillColor = [UIColor orangeColor].CGColor;
    shapeLayer.lineWidth = 3;
    shapeLayer.path = path.CGPath;
    
    //漸變色layer
    CAGradientLayer *gradiLayer = [CAGradientLayer layer];
    gradiLayer.colors = @[(__bridge id)[UIColor blueColor].CGColor,(__bridge id)[UIColor yellowColor].CGColor,(__bridge id)[UIColor redColor].CGColor];
    gradiLayer.frame = CGRectMake(0, 0, 200, 100);
    gradiLayer.locations = @[@(0),@(0.3),@(1)];
    gradiLayer.startPoint = CGPointMake(0.5, 0);
    gradiLayer.endPoint = CGPointMake(0.5, 1);
    
    [backView.layer addSublayer:gradiLayer];
    [backView.layer addSublayer:shapeLayer];
    
    //遮罩範圍之外的部分不會顯示
    gradiLayer.mask = shapeLayer;