Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Animated Gradient view with overlay to be used as a "skeleton" view in the Mimir app
//
// SkeletonGradientAnimationView.swift
// Mimir
//
// Created by Grant Davis on 3/18/22.
// Copyright © 2022 Grant Davis Interactive, LLC. All rights reserved.
//
import Foundation
import SwiftUI
public struct SkeletonGradientAnimationView: View {
@State var offset: CGFloat = 0
public var body: some View {
ZStack {
GeometryReader { reader in
let largestSide = reader.size.width > reader.size.height ? reader.size.width : reader.size.height
LinearGradient(
stops: [
Gradient.Stop(color: .white.opacity(0), location: 0.333),
Gradient.Stop(color: .white, location: 0.5),
Gradient.Stop(color: .white.opacity(0), location: 0.666),
],
startPoint: UnitPoint(x: 0, y: 0),
endPoint: UnitPoint(x: 1, y: 1)
)
.frame(width: largestSide * 2.0, height: largestSide * 2, alignment: .leading)
.mask(
LinearGradient(colors: [.clear, .white, .white, .clear], startPoint: .leading, endPoint: .trailing)
)
.blendMode(.overlay)
.offset(x: -largestSide * 2 + offset, y: reader.size.height * 0.5 - largestSide)
.onAppear {
withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: false)) {
offset = largestSide * 3
}
}
}
}
}
}
struct SkeletonGradientAnimationView_Preview: PreviewProvider {
static var previews: some View {
VStack {
SkeletonGradientAnimationView()
.background(Color.green)
.frame(width: 375, height: 232)
.mask(
RoundedRectangle(cornerRadius: 16)
)
ZStack {
SkeletonGradientAnimationView()
.background(Color.blue)
.frame(width: 256, height: 320)
.mask(
VStack(spacing: 8) {
RoundedRectangle(cornerRadius: 8)
.frame(width: 256, height: 256)
HStack(alignment: .top, spacing: 4) {
VStack(spacing: 4) {
RoundedRectangle(cornerRadius: 8)
.frame(height: 16)
RoundedRectangle(cornerRadius: 8)
.frame(height: 16)
}
Ellipse()
.frame(width: 24, height: 24)
}
}
)
}
}
}
}
@hoangnam714
Copy link

hoangnam714 commented Aug 26, 2022

Thank you it works quite well

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