Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparency gradient on UIImageView

I would imagine what I am trying to do is quite simple, but I can't seem to figure it out. I know how to apply a gradient on a UIImage using an UIImageView, but that is not what I want. What I want to do is, while keeping the image bounds, is to fade out the top half of a UIImage so it is fully transparent. I want to be able to see the view behind the UIImage with the bottom half of the image still fully visible (not opaque).

Any ideas? Any help would be greatly appreciated.

like image 720
thunderousNinja Avatar asked Jun 04 '14 00:06

thunderousNinja


1 Answers

The easiest way to do this is to use a CAGradientLayer as a layer mask—in other words, use its opacity to determine the opacity of the layer it’s attached to. Something along these lines should do the trick:

CALayer *imageViewLayer = theImageView.layer;
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.colors = @[ (id)([UIColor blackColor].CGColor), (id)([UIColor clearColor].CGColor) ]; // gradient from 100% opacity to 0% opacity (non-alpha components of the color are ignored)
// startPoint and endPoint (used to position/size the gradient) are in a coordinate space from the top left to bottom right of the layer: (0,0)–(1,1)
maskLayer.startPoint = CGPointMake(0, 0.5); // middle left
maskLayer.endPoint = CGPointMake(0, 0); // top left
maskLayer.frame = imageViewLayer.bounds; // line it up with the layer it’s masking
imageViewLayer.mask = maskLayer;
like image 179
Noah Witherspoon Avatar answered Nov 25 '22 20:11

Noah Witherspoon