How to fill a shape defined with CGPoints with gradient in iOS?

Posted on

How to fill a shape defined with CGPoints with gradient in iOS?

I have a custom shape of an arrow set up in code. What I’m trying to do is fill it with gradient. Problem is, I have no idea how to fill a non rectangular shape (space inside dark frame) with gradient. Any ideas?

 //Define colours used in drawing
CGContextRef context = UIGraphicsGetCurrentContext();

CGColorRef lightColor = _lightColor.CGColor;
CGColorRef darkColor = _darkColor.CGColor;
CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 
 blue:0.2 alpha:0.5].CGColor;   

//Get label text size to help determine sizes for drawing
CGSize textSize = [[_titleLabel text] sizeWithFont:[_titleLabel font]];

//Set shadow
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(0, 2), 3.0, shadowColor);

//Set arrow shape
CGPoint rectangle_points[] =
{
    CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y),
    CGPointMake(textSize.width+10, _coloredBoxRect.origin.y),
    CGPointMake(textSize.width+40, _coloredBoxRect.origin.y+20),
    CGPointMake(textSize.width+10, _coloredBoxRect.origin.y+40),
    CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y+40),
    CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y),
};
CGContextAddLines(context, rectangle_points, 6);    
CGContextSetFillColorWithColor(context, lightColor);
CGContextFillPath(context);

CGContextRestoreGState(context);

//Draw dark frame for the arrow
CGContextSetStrokeColorWithColor(context, darkColor);
CGContextSetLineWidth(context, 1.0);  
CGContextSaveGState(context);
draw1PxStroke(context, CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y), CGPointMake(textSize.width+10, _coloredBoxRect.origin.y), darkColor);
draw1PxStroke(context, CGPointMake(textSize.width+10, _coloredBoxRect.origin.y+40), CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y+40), darkColor);
draw1PxStroke(context, CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y), CGPointMake(_coloredBoxRect.origin.x, _coloredBoxRect.origin.y+40), darkColor);
draw1PxStroke(context, CGPointMake(textSize.width+10, _coloredBoxRect.origin.y), CGPointMake(textSize.width+40, _coloredBoxRect.origin.y+20), darkColor);
draw1PxStroke(context, CGPointMake(textSize.width+10, _coloredBoxRect.origin.y+40), CGPointMake(textSize.width+40, _coloredBoxRect.origin.y+20), darkColor);    
CGContextRestoreGState(context);

Solution :

Check out this apple sample application.
It has exactly what u need in the “Polygons” section (for filling a polygon).
What you need to change is drawing the gradient instead of drawing as in the example.
Drawing gradients is also exemplified in the sample, under the “Gradients” section.

http://developer.apple.com/library/ios/#samplecode/QuartzDemo/Introduction/Intro.html

Hope this helps,
Vlad

Leave a Reply

Your email address will not be published. Required fields are marked *