Search code examples
iosquartz-graphicscgpath

Draw CGGradient On Enclosed Path


How does one draw a CGGradient on an enclosed path within a view? I have attempted to draw the gradient, however, it is drawn on the view itself, rather than only within a CGPath that I am filling inside the view. I would like to draw a gradient on the filled path only, and not on the view itself.


Solution

    1. Save the context's state.
    2. Set the path as a clip region in your context.
    3. Draw the gradient.
    4. Restore the context's state.

    Example:

    CGContextSaveGState(context);
    CGContextAddPath(context, myPath);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kNilOptions);
    CGContextRestoreGState(context);