Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate Layer Opacity with UIView.Animate

I have 2 CALayers, each with an image. Both have an initial Opacity of 0.

I want to animate Layer1's Opacity to 1 over 1 second, starting straight away. Then after a delay of 0.5 seconds, I want to animate Layer2's Opacity to 1 over 1 second. These 2 layers sit on top of one another.

What I am trying to achieve is having the first image fade in, then while it is fading in, fade the second image over it.

But I cannot use UIView.Animate for some reason as it does not animate at all, just sets the values straight away.

        UIView.Animate(1, 0, UIViewAnimationOptions.CurveEaseIn, () => 
        {
            backgroundLayer.Opacity = 1;
        }, () => UIView.Animate(5, () => 
        {
            backgroundLayer2.Opacity = 1;
        }));

Here is simply tried to run the animation straight after one another and it still just sets the values right away and there is no animation.

like image 512
David Pilkington Avatar asked Feb 01 '26 23:02

David Pilkington


2 Answers

UIView animations are intended for animating UIView properties and don't seem to play well with CALayers. Using UIImageViews instead of CALayers would solve your problem (then you should use the imageView.alpha property instead of the layer.opacity property).

However, if you insist on using CALayers you can animate them with CABasicAnimation. The code below accomplishes the animation you described (note that this is Swift code, as I don't use Xamarin).

    var animation1 = CABasicAnimation(keyPath: "opacity")
    // Don't go back to the initial state after the animation.
    animation1.fillMode = kCAFillModeForwards
    animation1.removedOnCompletion = false

    // Set the initial and final states of the animation.
    animation1.fromValue = 0
    animation1.toValue = 1

    // Duration of the animation.
    animation1.duration = 1.0


    var animation2 = CABasicAnimation(keyPath: "opacity")
    animation2.fillMode = kCAFillModeForwards
    animation2.removedOnCompletion = false

    animation2.fromValue = 0
    animation2.toValue = 1

    animation2.duration = 1.0

    // Add a 0.5 second delay.
    animation2.beginTime = CACurrentMediaTime() + 0.5

    // Animate!
    backgroundLayer.addAnimation(animation1, forKey: "opacity")
    backgroundLayer2.addAnimation(animation2, forKey: "opacity")
like image 82
bjornorri Avatar answered Feb 03 '26 13:02

bjornorri


You can only animate following properties with UIView.Animate:

  • UIView.Frame
  • UIView.Bounds
  • UIView.Center
  • UIView.Transform
  • UIView.Alpha
  • UIView.BackgroundColor
  • UIView.ContentStretch

For more sophisticated animations you have to use CABasicAnimation like in @bjornorri answer.

like image 44
fex Avatar answered Feb 03 '26 12:02

fex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!