Skip to content

Instantly share code, notes, and snippets.

@tgrapperon
Last active December 31, 2022 06:25
Show Gist options
  • Save tgrapperon/8d77cf873aee34a648c4f3283d97dcae to your computer and use it in GitHub Desktop.
Save tgrapperon/8d77cf873aee34a648c4f3283d97dcae to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
@State var selected = 0
@State var count: Int = 100
@State var position: CGPoint = .zero
var body: some View {
VStack {
Picker(selection: $selected) {
Text("Mask").tag(0)
Text("ClipShape").tag(1)
Text("Background").tag(2)
Text("Background Style").tag(3)
} label: {
Text("Type")
}.pickerStyle(.segmented)
Stepper("Count: \(count)") {
count += 100
} onDecrement: {
count -= 100
count = max(0, count)
}
let content = Text("Hello")
let shadowShape = Ellipse()
ZStack {
Color.clear
ForEach(Array(0..<count), id: \.self) { _ in
switch selected {
case 0:
MaskView {
shadowShape
} content: {
content
}
case 1:
ClipView {
shadowShape
} content: {
content
}
case 2:
BackgroundView {
shadowShape
} content: {
content
}
case 3:
BackgroundView2 {
shadowShape
} content: {
content
}
default:
fatalError()
}
}
.offset(
x: position.x,
y: position.y
)
}
.task {
while true {
try? await Task.sleep(for: .milliseconds(50))
self.position = CGPoint(
x: CGFloat.random(in: 0...150),
y: CGFloat.random(in: 0...150)
)
}
}
}
}
}
struct MaskView<Content: View, ShadowShape: Shape>: View {
let content: Content
let shadowShape: ShadowShape
init(
shadowShape: () -> ShadowShape,
@ViewBuilder content: () -> Content
) {
self.shadowShape = shadowShape()
self.content = content()
}
var body: some View {
content
.mask(shadowShape)
.shadow(radius: 10)
}
}
struct ClipView<Content: View, ShadowShape: Shape>: View {
let content: Content
let shadowShape: ShadowShape
init(
shadowShape: () -> ShadowShape,
@ViewBuilder content: () -> Content
) {
self.shadowShape = shadowShape()
self.content = content()
}
var body: some View {
content
.clipShape(shadowShape)
.shadow(radius: 10)
}
}
struct BackgroundView<Content: View, ShadowShape: Shape>: View {
let content: Content
let shadowShape: ShadowShape
init(
shadowShape: () -> ShadowShape,
@ViewBuilder content: () -> Content
) {
self.shadowShape = shadowShape()
self.content = content()
}
var body: some View {
content
.background(
shadowShape.shadow(radius: 10)
)
}
}
struct BackgroundView2<Content: View, ShadowShape: Shape>: View {
let content: Content
let shadowShape: ShadowShape
init(
shadowShape: () -> ShadowShape,
@ViewBuilder content: () -> Content
) {
self.shadowShape = shadowShape()
self.content = content()
}
var body: some View {
content
.background(
shadowShape.fill(.black.shadow(.drop(radius: 10)))
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment