Animating 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 Opacity

to 1

over 1 second starting right away. Then, after a 0.5 second delay, I want to animate Layer2 Opacity

to 1

over 1 second. These 2 layers are stacked on top of each other.

What I'm trying to achieve is that the first image fades out and then, when it fades out, fades out in the second image.

But I can't use UIView.Animate

for some reason as it doesn't animate at all, just sets the values ​​right away.

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

      

Just try to run the animation right next to each other and it still just sets the values ​​right away and there is no animation.

+3


source to share


3 answers


You guys are correct in that I am trying to animate layers using the wrong methods. As a result, I replaced the layers UIImageView

and used them UIView.Animate

to change properties Alpha

.



Not only was it easier for the code, it UIImageView

actually seems to be more efficient when it comes to images.

+1


source


UIView animation is meant to animate UIView properties and doesn't seem to work very well with CALayers. Using UIImageViews instead of CALayers will 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 describes the animation (note that this is Swift code as I am not using 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")

      

+3


source


You can animate the following properties with UIView.Animate:

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

For more complex animations, you need to use CABasicAnimation as in @ bjornorri's answer.

+1


source







All Articles