如何在drawRect中填充渐变路径:?

Der*_*ick 40 iphone core-graphics quartz-graphics drawrect

用纯色填充路径很容易:

CGPoint aPoint;
for (id pointValue in points)
{
    aPoint = [pointValue CGPointValue];
    CGContextAddLineToPoint(context, aPoint.x, aPoint.y);
}
[[UIColor redColor] setFill];
[[UIColor blackColor] setStroke];
CGContextDrawPath(context, kCGPathFillStroke);
Run Code Online (Sandbox Code Playgroud)

我想绘制渐变而不是纯红色,但我遇到了麻烦.我已经尝试了问题/答案中列出的代码:iPhone上的UIView和UILabels上的渐变

这是:

CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:rect];
[gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor],
                (id)[[UIColor whiteColor] CGColor], nil]];
[[self layer] setMasksToBounds:YES];

[[self layer] insertSublayer:gradient atIndex:0];
Run Code Online (Sandbox Code Playgroud)

然而,这描绘了整个视图,它与渐变一起,掩盖了我的原始路径.

sbo*_*oth 97

我会剪切到你要填充的路径,并使用CGContextDrawLinearGradient.这是drawRect的一个简单实现:作为一个例子:

- (void) drawRect:(CGRect)rect
{
    // Create a gradient from white to red
    CGFloat colors [] = { 
        1.0, 1.0, 1.0, 1.0, 
        1.0, 0.0, 0.0, 1.0
    };

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient), gradient = NULL;

    CGContextRestoreGState(context);

    CGContextAddEllipseInRect(context, rect);
    CGContextDrawPath(context, kCGPathStroke);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果能给你一个很棒的徽章,我会的!您知道有关CGContextSaveGState和其他内容的任何教程吗?因为苹果类的参考很薄。 (2认同)