title: iOS Animate Mask Over UIImage
body: <p>I am using Swift 1.2 and my goal is to animate an image mask over a static UIImage. What I have implemented is a swift version of masking an image that I originally found in Objective-C. </p>
  
  <pre><code>func maskImage(image: UIImage, mask: UIImage) -&gt; UIImage! {
  
      let maskRef = mask.CGImage;
  
      let mask = CGImageMaskCreate(
          CGImageGetWidth(maskRef),
          CGImageGetHeight(maskRef),
          CGImageGetBitsPerComponent(maskRef),
          CGImageGetBitsPerPixel(maskRef),
          CGImageGetBytesPerRow(maskRef),
          CGImageGetDataProvider(maskRef), nil, false);
  
      let masked = CGImageCreateWithMask(image.CGImage, mask);
      let retImage = UIImage(CGImage: masked);
      return retImage;
  }
  </code></pre>
  
  <p>It works great! However, putting it in motion is my challenge.</p>
  
  <p>Is there a way to either iteratively apply the mask with a different horizontal offset or a better way to approach this problem entirely - perhaps with a CALayer implementation?</p>
  
  <p>Thanks for your help!</p>
  
  <p><strong>EDIT:</strong> Based on what was posted as an answer, I added this:</p>
  
  <pre><code>    let image = UIImage(named: "clouds");
  
      let imageView = UIImageView(image: image);
      let layer = CALayer();
      layer.contents = UIImage(named: "alpha-mask")?.CGImage;
      layer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
  
      // For other folks learning, this did not work
      //let animation = CABasicAnimation(keyPath: "bounds.origin.x");
  
      // This does work
      let animation = CABasicAnimation(keyPath: "position.x");
  
      animation.duration = 2;
      animation.delegate = self;
      animation.fillMode = kCAFillModeForwards;
      animation.repeatCount = 0;
      animation.fromValue = 0.0;
      animation.toValue = image.size.width;
      animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear);
      animation.removedOnCompletion = false;
  
      layer.addAnimation(animation, forKey: "transform");
  
      imageView.layer.mask = layer;
  
      self.addSubview(imageView);
  </code></pre>
  
  <p>I am able to see the alpha mask properly, but the animation does not work. Any ideas?</p>
  
  <p><strong>EDIT:</strong> I modified the code above and it works! I needed to make the keyPath position.x. See above</p>