How to fill a path with gradient in drawRect:?

前端 未结 1 1899
再見小時候
再見小時候 2020-12-12 12:07

filling a path with a solid color is easy enough:

CGPoint aPoint;
for (id pointValue in points)
{
    aPoint = [pointValue CGPointValue];
    CGContextAddLin         


        
1条回答
  •  旧巷少年郎
    2020-12-12 12:48

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

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