Skip to content

Instantly share code, notes, and snippets.

@chrismiles
Created June 8, 2011 02:04
Show Gist options
  • Save chrismiles/1013641 to your computer and use it in GitHub Desktop.
Save chrismiles/1013641 to your computer and use it in GitHub Desktop.
Core Graphics Extra Convenience Functions
/*
Example:
CGRect fillRect = CGRectMake(0.0, 0.0, 50.0, 100.0);
size_t locationCount = 2;
CGFloat locationList[] = {0.0, 1.0};
CGFloat colorList[] = {
//red, green, blue, alpha
244.0/255.0, 207.0/255.0, 80.0/255.0, 1.0,
255.0/255.0, 161.0/255.0, 59.0/255.0, 1.0,
};
CGContextGradientFillRect(c, fillRect, locationList, locationCount, colorList);
*/
void
CGContextGradientFillRect(CGContextRef c, CGRect fillRect, CGFloat *locationList, size_t locationCount, CGFloat *colorList)
{
CGContextSaveGState(c);
CGContextAddRect(c, fillRect);
CGContextClip(c);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef myGradient = CGGradientCreateWithColorComponents(rgbColorSpace, colorList, locationList, locationCount);
CGPoint startPoint = CGPointMake(CGRectGetMinX(fillRect), CGRectGetMinY(fillRect));
CGPoint endPoint = CGPointMake(CGRectGetMinX(fillRect), CGRectGetMaxY(fillRect));
CGContextDrawLinearGradient(c, myGradient, startPoint, endPoint, 0);
CGGradientRelease(myGradient);
CGColorSpaceRelease(rgbColorSpace);
CGContextRestoreGState(c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment