Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent (alpha) gradient with Core Graphic iPhone

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: enter image description here

like image 731
Pablosproject Avatar asked Aug 04 '12 10:08

Pablosproject


2 Answers

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; 
like image 183
Matthew Horst Avatar answered Oct 11 '22 21:10

Matthew Horst


Swift 3 - This is what worked for me. I needed only 20% of bottom image to be transparent with gradient.

    // Create the gradient layer     let gradientLayer = CAGradientLayer()     gradientLayer.frame = imageView.bounds      gradientLayer.colors = [         UIColor.white.withAlphaComponent(1).cgColor,         UIColor.white.withAlphaComponent(0).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 = CGPoint(x: 0.0, y: 0.80)     gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)     // Use the gradient layer as the mask     imageView.layer.mask = gradientLayer 

enter image description here

like image 28
Arijan Avatar answered Oct 11 '22 21:10

Arijan