title: Masking an image in Swift using CALayer and UIImage
body: <p>I'm programming in Swift.  I want to mask an image using CALayer and UIImage.  I'm creating my mask image programmatically.  The created mask image is a UIImage and works fine when I view it on its own.  But when I use it as a mask the whole screen becomes white.  I suspect that my problem is in configuring the CALayer object.  I would appreciate your help.  Thanks!</p>
  
  <pre><code>class ViewController: UIViewController {
  
      @IBOutlet weak var imageView: UIImageView!
  
      override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view, typically from a nib.
          var maskImageSize = CGSizeMake(self.imageView.frame.width, self.imageView.frame.height)
          UIGraphicsBeginImageContextWithOptions(maskImageSize, false, 0.0)
  
          var color = UIColor(white: 1.0, alpha: 1.0)
          color.setFill()
          var rect = CGRectMake(0, 0, self.imageView.frame.width, self.imageView.frame.height)
          UIRectFill(rect)
  
          color = UIColor(white: 0.0, alpha: 1.0)
          color.setFill()
          rect = CGRectMake((self.imageView.frame.width/2)-100, (self.imageView.frame.height/2)-100, 200, 200)
          UIRectFill(rect)
  
          var maskImage = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
  
          var maskLayer = CALayer()
          maskLayer.contents = maskImage
          maskLayer.contentsRect = CGRectMake(0, 0, self.imageView.bounds.width, self.imageView.bounds.height)
  
  
          self.imageView.image = UIImage(named: "pictobemasked.png")
  
          self.imageView.layer.mask = maskLayer;
      }
  
  }
  </code></pre>