anyone knows how to programmatically create a transparent gradient (alpha gradient), over an image with Core Graphic? I need it both for display an image and save it.
An example of what I want to obtain:
You can use QuartzCore to apply a mask (with gradient transparency) to the UIImageView:
UIImageView *myImageView = ["the image view"];
CAGradientLayer *l = [CAGradientLayer layer];
l.frame = myImageView.bounds;
l.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0] CGColor], (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor], nil];
l.startPoint = CGPointMake(0.0, 0.0f);
l.endPoint = CGPointMake(1.0f, 1.0f);
//you can change the direction, obviously, this would be top to bottom fade
myImageView.layer.mask = l;
To save it you can find the answer easily here on Stack Overflow, just by searching for how to save the contents of the canvas to a UIImage.
Or Swift version as requested by @Zazu:
// Whatever you image view is, obviously not hardcoded like this
let imageView = UIImageView.init(image: UIImage(named: "Image"))
imageView.frame = CGRectMake(0, 0, 320, 480)
self.view.addSubview(imageView)
// Create the gradient layer
let gradientLayer = CAGradientLayer.init()
gradientLayer.frame = imageView.bounds
gradientLayer.colors = [
UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0).CGColor,
UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1).CGColor]
// Whatever direction you want the fade. You can use gradientLayer.locations
// to provide an array of points, with matching colors for each point,
// which lets you do other than just a uniform gradient.
gradientLayer.startPoint = CGPointMake(1.0, 0.0);
gradientLayer.endPoint = CGPointMake(0.0, 0.0);
// Use the gradient layer as the mask
imageView.layer.mask = gradientLayer;