Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
iOS smooth gradient using CGShading
- (void)drawRect:(CGRect)rect {
// Draw the gradient background
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// Define the shading callbacks
CGFunctionCallbacks callbacks = {0, blackShade, NULL};
// As input to our function we want 1 value in the range [0.0, 1.0].
// This is our position within the 'gradient'.
size_t domainDimension = 1;
CGFloat domain[2] = {0.0f, 1.0f};
// The output of our function is 2 values, each in the range [0.0, 1.0].
// This is our selected color for the input position.
// The 2 values are the white and alpha components.
size_t rangeDimension = 2;
CGFloat range[8] = {0.0f, 1.0f, 0.0f, 1.0f};
// Create the shading finction
CGFunctionRef function = CGFunctionCreate(NULL, domainDimension, domain, rangeDimension, range, &callbacks);
// Create the shading object
CGShadingRef shading = CGShadingCreateAxial(colorSpace, CGPointMake(1, rect.size.height), CGPointMake(1, rect.size.height*0.75f), function, YES, YES);
// Draw the shading
CGContextDrawShading(context, shading);
// Clean up
// This is the callback of our shading function.
static void blackShade(void *info, const CGFloat *inData, CGFloat *outData) {
float p = inData[0];
outData[0] = 0.0f;
outData[1] = (1.0f-slope(p, 2.0f)) * 0.5f;
// ristributes values on a slope (ease-in ease-out)
static float slope(float x, float A) {
float p = powf(x, A);
return p/(p + powf(1.0f-x, A));

This comment has been minimized.

Copy link

@lucamegh lucamegh commented Jul 27, 2015

Hello Jernej,
I tried to reach you out on Twitter but I guess that talking here is more appropriate. I've been looking for a smooth gradient solution for days and then I found your article just about a few hours ago but, being a junior developer, and your code is pretty complicated for me to understand! I needed to create a smooth gradient that goes from a transparent color to whatever color I need. I tried editing your code (tried using CGColorSpaceCreateDeviceRGB()) without success. Could you help me out? I would appreciate that so much.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment