iosswiftstringcabasicanimation

Draw string with alpha animation


I am drawing a string on a view as

string.draw(at: point withAttributes: attributes)

I want to add some animation effect to the string, basically the alpha value - from 0 to 1 for a duration of 1.0 second. How would I achieve it?


Solution

  • You can animate the view layer opacity with CABasicAnimation, i.e:

    let view = // view rendering string
    
    let animation = CABasicAnimation(keyPath: "opacity")
    animation.fromValue = 0
    animation.toValue = 1
    animation.duration = 1
    
    // add animation
    view.layer.add(animation, key: "opacity")
    
    // commit the final opacity value that will be used after animation completes
    view.layer.opacity = 1
    

    You may also want to use CATextLayer instead of rendering the string in UIView.draw. In that case you would animate the opacity of the text layer.

    let view = // view rendering string
    
    let textLayer = CATextLayer()
    textLayer.string = "my text"
    textLayer.frame = view.layer.bounds
    
    view.layer.addSublayer(textLayer)