UIBezierPath with color gradient

前端 未结 5 1731
孤街浪徒
孤街浪徒 2021-02-08 15:21

I\'ve got an question about UIBezierPath.

For example I\'ve got this path:

\"\"

Now I want to have

5条回答
  •  耶瑟儿~
    2021-02-08 15:36

    Use CAGradientLayer and mask it using CAShapeLayer Something like this

    - (void)addCircle{
        CAShapeLayer *shapeLayer = [CAShapeLayer new];
        shapeLayer.path = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(10, 10, 100, 100), 4, 4)].CGPath;
        shapeLayer.strokeColor = [UIColor redColor].CGColor;
        shapeLayer.contentsScale = [UIScreen mainScreen].scale;
        shapeLayer.shouldRasterize = NO;
    
    
        CAGradientLayer *_gradientLayer = [CAGradientLayer layer];
        _gradientLayer.frame =self.view.bounds;
        _gradientLayer.startPoint = CGPointMake(0.0, 1);
        _gradientLayer.endPoint = CGPointMake(1, 0);
        _gradientLayer.colors = @[(id)[UIColor blueColor].CGColor,(id)[UIColor redColor].CGColor];
    
        //Add gradient layer to view
        [self.view.layer addSublayer:_gradientLayer];
        _gradientLayer.mask = shapeLayer;
    }
    

    Above method will add a triangle may be you need to change start and end points. Also you can change gradient values to whatever you need.

    Apple Docs

    CAGradientLayer Tutorial

    Update After update its more clear that its not triangle you want, but what you need is possible with CAGradientLayer and CAShapeLayer, you need to follow same approach where you can add gradient with different colors and locations (stops)(if you are adding locations then make sure locations and colors are equal) and then mask it with CAShapeLayer which was circle.

提交回复
热议问题