1

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? :)

Cœur
  • 37,241
  • 25
  • 195
  • 267
skålfyfan
  • 4,931
  • 5
  • 41
  • 59

1 Answers1

3

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.

kamartem
  • 994
  • 1
  • 12
  • 22
Victor
  • 3,497
  • 3
  • 39
  • 51