Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically add a Gradient Layer over an image in Swift?

I want to place a layer with a predefined Transparent to Black gradient on top of an UIImage whose content image is loaded via web and creating an effect of a shadow over it.

I don't want to do it via loading a png with such a gradient.

like image 976
Hugo Alonso Avatar asked Apr 14 '15 16:04

Hugo Alonso


1 Answers

I suggest creating a custom subclass of UIView (or UIImageView, if what you want to add the gradient to is a UIImageView). In the init method of your custom view, create a CAGradientLayer and add it as a sublayer of your view's layer. Then set up the black to transparent gradient on the layer.

You will probably need to override layoutSubviews() and change the settings on your gradient layer in case the view's bounds change.

EDIT:

I created a playground as a gist on github that is a working example of this:

The code looks like this:

import UIKit
import AVFoundation


class ImageViewWithGradient: UIImageView
{
  let myGradientLayer: CAGradientLayer

  override init(frame: CGRect)
  {
    myGradientLayer = CAGradientLayer()
    super.init(frame: frame)
    self.setup()
  }

  required init(coder aDecoder: NSCoder)
  {
    myGradientLayer = CAGradientLayer()
    super.init(coder: aDecoder)
    self.setup()
  }

  func setup()
  {
    myGradientLayer.startPoint = CGPoint(x: 0, y: 0)
    myGradientLayer.endPoint = CGPoint(x: 1, y: 1)
    let colors: [CGColorRef] = [
      UIColor.clearColor().CGColor,
      UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor,
      UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).CGColor,
      UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor,
      UIColor.clearColor().CGColor ]
    myGradientLayer.colors = colors
    myGradientLayer.opaque = false
    myGradientLayer.locations = [0.0,  0.3, 0.5, 0.7, 1.0]
    self.layer.addSublayer(myGradientLayer)
  }

  override func layoutSubviews()
  {
    myGradientLayer.frame = self.layer.bounds
  }
}


var aView = ImageViewWithGradient(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
like image 178
Duncan C Avatar answered Sep 23 '22 13:09

Duncan C