SwiftUI如何实现文本在红、橙、黄三色间的颜色脉动动画?
修改SwiftUI文本颜色脉动为三色循环
要实现文本在红、橙、黄三种颜色间循环脉动,需要调整颜色数组并重构动画逻辑(原逻辑仅支持双色来回切换),具体修改如下:
关键修改点
- 扩展颜色数组,加入红色
- 改用
Timer实现循环的颜色索引切换,模拟三色脉动路径:红→橙→黄→橙→红→... - 给颜色变化绑定动画,保证切换过程平滑自然
- 添加Timer销毁逻辑,避免内存泄漏
修改后的完整代码
struct PulsingText: View { // 更新颜色数组,加入红色 let colors = [Color.red, Color.orange, Color.yellow] @State private var colorIndex = 0 @State private var cycleTimer: Timer? var body: some View { Text("Hello World!") .foregroundColor(colors[colorIndex]) // 给颜色变化绑定动画,时长1秒,过渡平滑 .animation(.easeInOut(duration: 1), value: colorIndex) .font(.custom("HelveticaNeue-Bold", size: 32)) .kerning(-3.2) .onAppear { startColorCycle() } .onDisappear { // 页面消失时停止Timer,避免内存泄漏 cycleTimer?.invalidate() } } private func startColorCycle() { // 定义三色脉动的索引切换序列:红(0)→橙(1)→黄(2)→橙(1)→红(0)... let indexSequence = [1, 2, 1, 0] var sequenceIndex = 0 // 每隔1秒切换一次颜色索引 cycleTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in colorIndex = indexSequence[sequenceIndex % indexSequence.count] sequenceIndex += 1 } } }
效果说明
文本颜色会按照红色→橙色→黄色→橙色→红色的顺序循环平滑过渡,每次颜色切换的动画时长为1秒,整体脉动节奏连贯自然。
内容的提问来源于stack exchange,提问作者RainCast
相关产品推荐
相关产品推荐

