如何在drawRect中填充渐变路径:? [英] How to fill a path with gradient in drawRect:?

查看:259
本文介绍了如何在drawRect中填充渐变路径:?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用纯色填充路径很容易:

filling a path with a solid color is easy enough:

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

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

I'd like to draw a gradient instead of solid red, but I am having trouble. I've tried the code listed in the Question/Answer: Gradients on UIView and UILabels On iPhone

这是:

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];

但是,这会绘制整个视图,它与渐变一起显示,覆盖了原始路径。

However, this paints the entire view that this is in with the gradient, covering up my original path.

推荐答案

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

I would clip to the path you want to fill, and use CGContextDrawLinearGradient. Here is a simple implementation of drawRect: as an example:

- (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);
}

这篇关于如何在drawRect中填充渐变路径:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆