使用 alpha 动画绘制字符串

Draw string with alpha animation

我正在 view 上绘制 string 作为

string.draw(at: point withAttributes: attributes)

我想为字符串添加一些动画效果,基本上是 alpha 值 - 从 0 到 1,持续 1.0 秒。我将如何实现它?

您可以使用 CABasicAnimation 为视图 layer 不透明度设置动画,即:

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

您可能还想使用 CATextLayer 而不是在 UIView.draw 中呈现字符串。在这种情况下,您将为文本层的 opacity 设置动画。

let view = // view rendering string

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

view.layer.addSublayer(textLayer)

对您的要求的另一种理解:

打字机效果文字动画

一个字符一个字符,

  • 显示的字符,alpha 1

  • 要显示的字符,alpha 0


extension UILabel{
    func setTyping(text content: String, duration: TimeInterval = 5.0) {
      text = ""
      let dalay = duration / TimeInterval(content.count)
      let writingTask = DispatchWorkItem { [weak self] in
        guard let `self` = self else {return}
        content.forEach { char in
          DispatchQueue.main.async {
            self.text?.append(char)
          }
          Thread.sleep(forTimeInterval: dalay)
        }
      }
        
      let queue: DispatchQueue = .init(label: "typespeed", qos: .userInteractive)
      queue.asyncAfter(deadline: .now() + 0.05, execute: writingTask)
    }
}