Skip to content

Instantly share code, notes, and snippets.

@col
Last active May 23, 2024 02:21
Show Gist options
  • Save col/955309b77b8e22a4e8e020101c7531f8 to your computer and use it in GitHub Desktop.
Save col/955309b77b8e22a4e8e020101c7531f8 to your computer and use it in GitHub Desktop.
SwiftUI Animated Blur Background
//
// AnimatedBackground.swift
// Playground
//
// Created by Colin Harris on 23/5/24.
//
import SwiftUI
struct AnimatedBackground: View {
var body: some View {
FloatingBlur(
fill: AnyShapeStyle(.teal.gradient),
direction: .clockwise,
offset: CGSize(width: 75, height: 0)
).offset(y:-75)
FloatingBlur(
fill: AnyShapeStyle(.orange.gradient),
direction: .counterClockwise,
offset: CGSize(width: -100, height: 0)
)
FloatingBlur(
fill: AnyShapeStyle(.pink.gradient),
direction: .clockwise,
offset: CGSize(width: 75, height: -75)
).offset(y:75)
}
}
struct FloatingBlur: View {
var fill: AnyShapeStyle
var rotationDirection: RotationDirection
var offset: CGSize
@State var rotation: Double
init(fill: AnyShapeStyle, direction: RotationDirection, offset: CGSize) {
self.fill = fill
self.rotationDirection = direction
self.offset = offset
self.rotation = rotationDirection.startDegrees
}
var body: some View {
Circle()
.fill(fill)
.blur(radius: 80)
.frame(width: 250)
.offset(offset)
.rotationEffect(.degrees(rotation))
.onAppear {
withAnimation(.linear(duration: 10).repeatForever(autoreverses: false)) {
rotation = rotationDirection.endDegrees
}
}
}
}
enum RotationDirection {
case clockwise
case counterClockwise
var startDegrees: Double {
switch self {
case .clockwise:
return 0
case .counterClockwise:
return 360
}
}
var endDegrees: Double {
switch self {
case .clockwise:
return 360
case .counterClockwise:
return 0
}
}
}
#Preview {
AnimatedBackground()
}
@col
Copy link
Author

col commented May 23, 2024

demo-video.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment