Search code examples
uiimagecore-animationcalayercabasicanimation

How to animate a CALayer to have empty contents


I have a CALayer with an image in it, and it has several sublayers. I want to animate it to have no contents (no image), but continue showing the sublayers. This code does not work:

   CABasicAnimation *backgroundOut = [CABasicAnimation animationWithKeyPath:@"contents"];
   backgroundOut.toValue = [NSNull null];
   backgroundOut.fillMode = kCAFillModeForwards;
   backgroundOut.removedOnCompletion = NO;
   backgroundOut.duration = 3.0;
   [_backgroundLayer addAnimation:backgroundOut forKey:@"contents"];

Here is the only way I could get this to work:

   backgroundOut.toValue = (__bridge id)([UIImage imageNamed:@"blankImage"].CGImage); 

Note that I don't want to mess with the opacity or anything because this layer has sublayers that need to still be visible.

What is the proper way to animate to empty contents?


Solution

  • I decided this was the cleanest approach, since there was no other answer forthcoming:

        UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0);
        UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        CABasicAnimation *backgroundOut = [CABasicAnimation animationWithKeyPath:@"contents"];
        backgroundOut.toValue = (__bridge id)(blank.CGImage);
        backgroundOut.fillMode = kCAFillModeForwards;
        backgroundOut.removedOnCompletion = NO;
        backgroundOut.duration = 3.0;
    
        [_backgroundLayer addAnimation:backgroundOut forKey:@"contents"];