Máscara animada de iOS sobre UIImage
Estoy usando Swift 1.2 y mi objetivo es animar una máscara de imagen sobre un UIImage estático. Lo que he implementado es una versión rápida de enmascarar una imagen que encontré originalmente en Objective-C.
func maskImage(image: UIImage, mask: UIImage) -> 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;
}
¡Funciona muy bien! Sin embargo, ponerlo en movimiento es mi desafío.
¿Hay alguna manera de aplicar iterativamente la máscara con un desplazamiento horizontal diferente o una mejor manera de abordar este problema por completo, tal vez con una implementación de CALayer?
¡Gracias por tu ayuda!
EDITAR: Según lo publicado como respuesta, agregué esto:
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);
Puedo ver la máscara alfa correctamente, pero la animación no funciona. ¿Algunas ideas?
EDITAR: ¡Modifiqué el código anterior y funciona! Necesitaba hacer keyPath position.x. Véase más arriba