Search code examples
iphonecocoa-touchios4uinavigationbarquartz-graphics

Creating background gradients for a view programmatically? How?


I have a small view with a few buttons on it. I want to make this small views background a black gradient identical to the gradient when you set your UINavigation bar to Black Opaque?

Is this possible programmatically or do I need to try my best at Photoshop to copy it? :)


Solution

  • Simple override drawRect message for UIView and draw background:

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        GContextDrawLinearGradient(context, self.gradientLayer, CGPointMake(0.0, 0.0),
                                CGPointMake(0.0, self.frame.size.height), kCGGradientDrawsBeforeStartLocation);
    }
    

    For creating and caching gradient use this snippet (color components you should use your own).

    - (CGGradientRef)gradientLayer
    {
        if (_gradientLayer == nil)
        {
            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
            CGFloat locations[] = { 0.0, 1.0 };
            CGFloat colors[] = { 0.0 / 255.0, 0.0 / 255.0, 48.0 / 255.0, 1.00, 26.0 / 255.0, 48.0 / 255.0, 89.0 / 255.0, 1.00 };
    
            _gradientLayer = CGGradientCreateWithColorComponents(colorSpace, colors, locations, sizeof(colors) / (sizeof(colors[0]) * 4));
            CGColorSpaceRelease(colorSpace);
        }
        return _gradientLayer;
    }
    

    And of course don't forget release your gradient into dealloc.