Last active
March 14, 2025 03:04
-
-
Save Enie/f10f193c3605f6b739e42ec0cd8dfb3e to your computer and use it in GitHub Desktop.
Brushed Metal shader effect for SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
@main | |
struct BrushedMetalDemoApp: App { | |
var body: some Scene { | |
WindowGroup { | |
BrushedMetalView { | |
ContentView() | |
} | |
} | |
.windowStyle(.hiddenTitleBar) | |
.windowToolbarStyle(.unified) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct BrushedMetalView<Content: View>: View { | |
var content: () -> Content | |
var body: some View { | |
GeometryReader { geometry in | |
content() | |
.background{ | |
Rectangle() | |
.ignoresSafeArea() | |
.colorEffect(ShaderLibrary.brushedMetal(.float2(geometry.size))) | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
@State var text: String = "" | |
var body: some View { | |
VStack { | |
TextEditor(text: $text) | |
.padding() | |
} | |
.background(Color(cgColor: NSColor.textBackgroundColor.cgColor)) | |
.cornerRadius(8) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.padding() | |
.shadow(color:.white,radius: 0,y:1) | |
.shadow(color:.black,radius: 0,y:-1) | |
} | |
} | |
#Preview { | |
BrushedMetalView { | |
ContentView() | |
} | |
} |
struct BrassMetalModifier: ViewModifier {
static let darkWindowBackgroundColor =
CGColor(gray: 50/256, alpha: 1.0)
func body(content: Content) -> some View {
content.background {
Color(Self.darkWindowBackgroundColor) // effect works on this
.overlay {
GeometryReader { geometry in
Color.black // no effect??
.colorEffect(ShaderLibrary.brushedMetal(.float2(geometry.size)))
}
}
}
}
}
extension View {
func brushedMetal() -> some View {
modifier(BrassMetalModifier())
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preview on how it looks like.:
