-
Notifications
You must be signed in to change notification settings - Fork 1
/
ShimmerView.swift
83 lines (76 loc) · 2.8 KB
/
ShimmerView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// ShimmerView.swift
//
// Created by James Sedlacek on 8/9/22.
//
import SwiftUI
struct ShimmerView: View {
@State private var isAnimating: Bool
private let offset: CGFloat
private let rotationAngle: Angle
private let linearGradient: LinearGradient
private let animation: Animation
private let primaryColor: Color
private let shimmerColor: Color
private let size: CGSize
private let shimmerSize: CGSize
private let cornerRadius: CGFloat
init(rotationAngle: Angle = Angle(degrees: 70),
animationSpeed: CGFloat = 0.2,
primaryColor: Color = .black.opacity(0.2),
shimmerColor: Color = .white.opacity(0.6),
size: CGSize = CGSize(width: 350, height: 200),
cornerRadius: CGFloat = 10) {
self.offset = size.width * 1.5
self.isAnimating = false
self.rotationAngle = rotationAngle
self.linearGradient = LinearGradient(colors: [shimmerColor.opacity(0.1),
shimmerColor,
shimmerColor.opacity(0.1)],
startPoint: .top,
endPoint: .bottom)
self.animation = Animation.default.speed(animationSpeed).delay(0).repeatForever(autoreverses: false)
self.primaryColor = primaryColor
self.shimmerColor = shimmerColor
self.size = size
self.shimmerSize = CGSize(width: size.width * 1.5,
height: size.width * 1.5)
self.cornerRadius = cornerRadius
}
var body: some View {
primaryColor
.frame(width: size.width, height: size.height)
.overlay(shimmerLayer())
.cornerRadius(cornerRadius)
.onAppear {
withAnimation(animation) {
isAnimating.toggle()
}
}
}
private func shimmerLayer() -> some View {
return Rectangle()
.fill(linearGradient)
.frame(width: shimmerSize.width,
height: shimmerSize.height)
.rotationEffect(rotationAngle)
.offset(x: isAnimating ? offset : -offset)
}
}
struct ShimmerView_Previews: PreviewProvider {
static var previews: some View {
VStack {
HStack {
ShimmerView(size: CGSize(width: 60, height: 60))
VStack(alignment: .leading) {
ShimmerView(size: CGSize(width: 180, height: 13))
ShimmerView(size: CGSize(width: 120, height: 13))
ShimmerView(size: CGSize(width: 60, height: 13))
}
}
ShimmerView()
}
.padding()
.previewLayout(.sizeThatFits)
}
}