【问题标题】:Filling a path with a gradient on iOS在 iOS 上用渐变填充路径
【发布时间】:2012-04-06 14:16:36
【问题描述】:

CAShapeLayer 上,我画了一个封闭的UIBezierPath。我可以通过设置fillColor 来填充这个形状,但是我想用渐变来填充这个形状。如何设置CAGradientLayer使其剪辑到贝塞尔路径所勾勒的形状?

【问题讨论】:

    标签: ios uibezierpath cagradientlayer


    【解决方案1】:

    草稿示例如下:

    ...
    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);
    
    ...
    

    【讨论】:

    • 这很好,但你也应该释放渐变和色彩空间。
    • 因为原来的帖子有一个面具,我还在CGContextDrawLinearGradient之前添加了以下内容:CGContextAddPath(context, roundedRectanglePath.CGPath);CGContextClip(context);
    【解决方案2】:

    你想要的是一个面具。 CAGradientlayer 有一个 -setMask 方法,可以像这样将其剪辑到形状的边界:

    [gradientLayer setMask:shapeLayer];

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2011-02-19
      • 2019-11-03
      相关资源
      最近更新 更多