Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Forked from ArtSabintsev/CoreGraphicsGraident.m
Created February 19, 2013 19:05
Show Gist options
  • Save trfiladelfo/4988845 to your computer and use it in GitHub Desktop.
Save trfiladelfo/4988845 to your computer and use it in GitHub Desktop.
// Macros for the top and bottom colors of the gradient
#define kGradientTopColor {0.0f/255.0f, 0.0f/255.0f, 0.0f/255.0f, 1.0f}
#define kGradientBottomColor {209.0f/255.0f, 209.0f/255.0f, 209.0f/255.0f, 1.0f}
// Macro for the area that should be covered by the gradient
#define kGradientBounds self.bounds
// Customize your UIView (e.g., UIView, UILabel, UIButton, etc...) drawRect method
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat colorLocations[] = { 0.0f, 1.0f };
CGFloat topColorComponents[] = kGradientTopColor;
CGFloat bottomColorComponents[] = kGradientBottomColor;
CGColorRef topColor = CGColorCreate(colorSpace, topColorComponents);
CGColorRef bottomColor = CGColorCreate(colorSpace, bottomColorComponents);
CFMutableArrayRef colorArray = CFArrayCreateMutable(NULL, 2, &kCFTypeArrayCallBacks);
CFArrayAppendValue(colorArray, bottomColor);
CFArrayAppendValue(colorArray, topColor);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colorArray, colorLocations);
// Define the area, and the start & end point of the gradient. The following three lines define a linear, top-down gradient.
CGRect bounds = kGradientBounds;
CGPoint startPoint = CGPointMake(CGRectGetMidX(bounds), CGRectGetMinY(bounds));
CGPoint endPoint = CGPointMake(CGRectGetMidX(bounds), CGRectGetMaxY(bounds));
CGContextSaveGState(context);
CGContextAddRect(context, bounds);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CFRelease(topColor);
CFRelease(bottomColor);
CFRelease(colorArray);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment