Filling a path with a gradient on iOS

后端 未结 2 1889
小蘑菇
小蘑菇 2021-02-09 00:36

On a CAShapeLayer, I\'ve drawn a closed UIBezierPath. I can fill this shape by setting the fillColor, however I want to fill the shape wit

相关标签:
2条回答
  • 2021-02-09 01:12

    A draft example would be the following:

    ...
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    UIColor *gradientColor = [UIColor colorWithRed:0.51 green:0.0 blue:0.49 alpha:1.0];
    
    NSArray *gradientColors = [NSArray arrayWithObjects: 
                              (id)[UIColor blueColor].CGColor, 
                              (id)gradientColor.CGColor, 
                              (id)[UIColor redColor].CGColor, nil];
    CGFloat gradientLocations[] = {0, 0.5, 1};
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations);
    
    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 10, 200, 200) cornerRadius:6];
    CGContextSaveGState(context);
    [roundedRectanglePath fill];
    [roundedRectanglePath addClip];
    CGContextDrawLinearGradient(context, gradient, CGPointMake(10, 10), CGPointMake(210, 10), 0);
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
    
    ...
    
    0 讨论(0)
  • 2021-02-09 01:14

    What you want is a mask. CAGradientlayer has a -setMask method that can clip it to the bounds of your shape like so:

    [gradientLayer setMask:shapeLayer];

    0 讨论(0)
提交回复
热议问题