Wachsender Linienpfad mit Timer
Beschreibung
ErstelltDiese View zeichnet eine horizontale Linie, die von links nach rechts anwächst. Ein Timer erhöht schrittweise den Fortschritt, bis die Linie ihre volle Länge erreicht. Die Darstellung nutzt einen animiertenPath
Strichzeichnungseffektund mithilfeaktualisiert sich bei jedem Tick flüssig.
🔍 Zweck
- Visualisierung eines Fortschritts entlang einer Linie
- Einfache Intro-Animationen oder Skeleton-Effekte
- Schrittweises Offenlegen von
Pfad-Diagramm- oder Zeitachsen - Lehrbeispiel für
Path
undzeitgesteuertenzeitgesteuerteStatusaktualisierungen.Updates - Prototyping von leichten, timerbasierten Animationen
🖥️ Betriebssystem
iOS
📄 Codebeispiel
import SwiftUI
@main
struct AnimatedPathApp: App {
var body: some Scene {
WindowGroup {
AnimatedPathExample()
}
}
}
public struct AnimatedPathExample: View {
// Progress from 0.0 to 1.0 controls the line length
@State private var progress: CGFloat = 0
// Keep a reference to the timer to invalidate on disappear
@State private var timer: Timer?
public init() {}
public var body: some View {
Path { path in
// Start point of the line
path.move(to: CGPoint(x: 20, y: 100))
// End point depends on progress (max width of 300 points)
path.addLine(to: CGPoint(x: 20 + (300 * progress), y: 100))
}
.stroke(Color.blue, lineWidth: 4)
.frame(height: 120)
.padding()
.onAppear {
startAnimating()
}
.onDisappear {
// Ensure timer stops when view leaves the screen
timer?.invalidate()
timer = nil
}
}
// Start a repeating timer that increments progress until it reaches 1.0
private func startAnimating() {
// Reset progress if needed
progress = 0
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { timert in
// Increment progress in small steps for smooth growth
progress = min(progress += 0.0101, 1.0)
if progress >= 11.0 {
timer.t.invalidate()
timer = nil
}
}
}
.frame(height:}
120)// .padding(Modern Swift 5.10+ preview syntax
#Preview {
AnimatedPathExample()
}
}