Skip to content

Instantly share code, notes, and snippets.

@joogps
Last active January 17, 2022 02:05
Show Gist options
  • Save joogps/c4fba26ca063310a0b84d771ba7c6c83 to your computer and use it in GitHub Desktop.
Save joogps/c4fba26ca063310a0b84d771ba7c6c83 to your computer and use it in GitHub Desktop.
Inner shadows in SwiftUI
struct InnerShadow<S: InsettableShape>: View {
let shape: S
var color: Color
var thickness: CGFloat
var offset: CGSize
var blur: CGFloat
init(shape: S,
color: Color = .white.opacity(0.25),
thickness: CGFloat = 0.0,
offset: CGSize = .zero,
blur: CGFloat = 5.0) {
self.shape = shape
self.color = color
self.thickness = thickness
self.offset = offset
self.blur = blur
}
public var body: some View {
shape.fill(color).mask {
ZStack {
shape
.fill(.white)
shape
.inset(by: thickness)
.fill(.black)
.offset(offset)
.blur(radius: blur)
}.compositingGroup()
.luminanceToAlpha()
}
}
}
public extension View {
func innerShadow<S: InsettableShape>(shape: S,
color: Color = .white.opacity(0.25),
thickness: CGFloat = 0.0,
offset: CGSize = .zero,
blur: CGFloat = 5.0) -> some View {
self.overlay {
InnerShadow(shape: shape, color: color, thickness: thickness, offset: offset, blur: blur)
}
}
}
extension InsettableShape {
func innerShadow<S: InsettableShape>(shape: S,
color: Color = .white.opacity(0.25),
thickness: CGFloat = 0.0,
offset: CGSize = .zero,
blur: CGFloat = 5.0) -> some View {
InnerShadow(shape: self, color: color, thickness: thickness, offset: offset, blur: blur)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment