Question

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?

Was it helpful?

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"];

OTHER TIPS

Another approach might be to create a separate layer to contain your image that is a peer of your other layers, but just behind the other layers (you can use zposition to place it behind the other layers explicitly)--all contained within a root layer. Then, you can animate the image layer's alpha for a fade and won't have the overhead of creating an image on the fly and it won't then fade the other layers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top