iOS - How to draw gradient along a path

Viewed 333

This is the effect that I want to achieve:

enter image description here

This is the effect that I am having now:

enter image description here

Basically, I need to draw the gradient along the path of the arc, not linearly across the arc. I tried a lot of ways, some of them yield the same result, but some of them produced a result that is farther from expectation.

This is the code that I am having right now:

    CGFloat lineSize = 12;
    CGFloat radius = self.frame.size.width/2 - lineSize;

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //Define gradient
    CGFloat colors [] =
    {
        0.9451f, 0.5804f, 0.2431f, 1.0f,
        0.9922f, 0.9490f, 0.9020f, 1.0f,
        1.0f, 1.0f, 1.0f, 1.0f,
        0.8706f, 0.9020f, 0.9412f, 1.0f,
        0.2941f, 0.6863f, 0.9176f, 1.0f
    };

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

    //Define arc angle and points
    CGFloat startAngle = 3.0f/4.0f * M_PI;
    CGFloat endAngle = 1.0f/4.0f * M_PI;

    CGFloat a = radius * cos(45);
    CGFloat o = a * tan(45);

    CGFloat y = CGRectGetMidY(rect) + o;

    CGPoint startPoint = CGPointMake(0, y);
    CGPoint endPoint = CGPointMake(self.frame.size.width, y);

    CGMutablePathRef arc = CGPathCreateMutable();
    CGPathAddArc(arc, NULL, CGRectGetMidX(rect), CGRectGetMidY(rect), radius,
                 startAngle, endAngle, NO);

    CGPathRef strokedArc = CGPathCreateCopyByStrokingPath(arc, NULL, 10, kCGLineCapButt, kCGLineJoinMiter, 10);

    CGContextAddPath(ctx, strokedArc);
    CGContextClip(ctx);

    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);

I also tried changing this block of code:

CGMutablePathRef arc = CGPathCreateMutable();
    CGPathAddArc(arc, NULL, CGRectGetMidX(rect), CGRectGetMidY(rect), radius,
                 startAngle, endAngle, NO);

    CGPathRef strokedArc = CGPathCreateCopyByStrokingPath(arc, NULL, 10, kCGLineCapButt, kCGLineJoinMiter, 10);

    CGContextAddPath(ctx, strokedArc);
    CGContextClip(ctx);

    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);

to this block code:

CGContextAddArc(ctx, CGRectGetMidX(rect), CGRectGetMidY(rect), radius, startAngle, endAngle, NO);

CGContextSetLineWidth(ctx, lineSize);
CGContextSetLineCap(ctx, kCGLineCapRound);

CGContextReplacePathWithStrokedPath(ctx);
CGContextClip(ctx);

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

But still yields similar result as the one I am having now.

1 Answers
Related