如何为通过draw方法绘制在view上的string添加1秒alpha渐变动画
实现文字绘制alpha渐变动画的两种方案
直接通过draw(at:withAttributes:)绘制的静态内容本身没有动画属性,你需要把文字绘制和动画属性绑定,以下是两种常用的落地实现:
方案1:使用CATextLayer承载文字(推荐)
CATextLayer自带隐式动画,不需要手动处理绘制逻辑,性能更高,完全可以对齐你原有的绘制效果:
- 首先初始化CATextLayer,配置和你之前一致的文字、位置、样式属性:
let textLayer = CATextLayer() textLayer.string = yourString textLayer.position = point // 对齐你原有attributes里的字体配置 textLayer.font = yourFont textLayer.fontSize = yourFont.pointSize // 对齐你原有attributes里的文字颜色配置 textLayer.foregroundColor = yourTextColor.cgColor // 适配屏幕分辨率避免文字模糊 textLayer.contentsScale = UIScreen.main.scale // 初始透明度设为0 textLayer.opacity = 0 // 添加到目标view的图层上 view.layer.addSublayer(textLayer)
- 执行1秒的alpha渐变动画:
CATransaction.begin() CATransaction.setAnimationDuration(1) textLayer.opacity = 1 CATransaction.commit()
你原有attributes中的字间距、行高等其他配置,都可以对应映射到CATextLayer的对应属性上。
方案2:保留手动draw逻辑的实现
如果你一定要在UIView的draw(_ rect:)方法里自定义绘制文字,可以通过绑定动态透明度属性触发重绘实现动画:
- 给自定义绘制的View新增可动画的透明度属性:
class CustomDrawView: UIView { // 绑定文字绘制的透明度,变化时触发重绘 var textAlpha: CGFloat = 0 { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { super.draw(rect) // 调整原有绘制属性的透明度 var adjustedAttributes = attributes if let originColor = attributes[.foregroundColor] as? UIColor { adjustedAttributes[.foregroundColor] = originColor.withAlphaComponent(textAlpha) } // 执行你原有的绘制逻辑 string.draw(at: point, withAttributes: adjustedAttributes) } }
- 触发属性动画:
let drawView = CustomDrawView() // 先把view添加到视图层级中 UIView.animate(withDuration: 1) { drawView.textAlpha = 1 }
该方案每次透明度变化都会触发重绘,性能稍低于CATextLayer方案,仅适合文字需要复杂自定义绘制的场景。
内容的提问来源于stack exchange,提问作者iOS
相关产品推荐
相关产品推荐

