Overlay with Gradient and Transparency

If you want to add a gradient to a UIView with transparency, so that you can e.g. put it on top of a UIImageView as container for some text, and you can rely on iOS 3.0+ being available, you might use a layer for this.

You can safely rely on iOS 4.0+ being installed on people’s iPhone and iPad nowadays. Already back in January, 84% of iPhones were running iOS 4 according to Chitika, and even iOS 5 was already installed on 33% of all iOS devices after less than one week of availability according to Localystics.

Include QuartzCore/QuartzCore.h to your source file, and you can create a gradient overlay from solid black to full transparency this way:

UIView *overlayContainer =
  [[[UIView alloc] initWithFrame:
    CGRectMake(0, 0, kSizeWidth, kSizeHeight)]
    autorelease];
overlayContainer.backgroundColor = [UIColor clearColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = overlayContainer.bounds;
gradient.colors = [NSArray arrayWithObjects:
  (id)[[UIColor blackColor] CGColor],
  (id)[[UIColor clearColor] CGColor], nil];
[overlayContainer.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:overlayContainer];

Comments are closed.