Skip to content

Instantly share code, notes, and snippets.

@pitt500
Created November 18, 2023 16:43
Show Gist options
  • Save pitt500/1958982f02641de84024d6a321a95f68 to your computer and use it in GitHub Desktop.
Save pitt500/1958982f02641de84024d6a321a95f68 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
@State private var sliderValue: Double = 0.0
@State private var backgroundColor: Color = .red
let colors: [Color] = [.red, .orange, .yellow, .green, .blue, .purple, .pink, .mint, .indigo, .teal, .cyan, .brown, .black]
var body: some View {
ZStack {
Rectangle()
.ignoresSafeArea()
.foregroundColor(backgroundColor)
VStack {
Text("This is a Demo")
.font(.largeTitle)
.foregroundStyle(backgroundColor.adaptedTextColor())
.padding(40)
Slider(value: $sliderValue, in: 0...1)
.tint(backgroundColor.adaptedTextColor())
.padding()
}
}
.onAppear {
updateColor()
}
.onChange(of: sliderValue) {
updateColor()
}
}
private func updateColor() {
let colorIndex = Int(sliderValue * Double(colors.count - 1))
backgroundColor = colors[colorIndex]
}
}
#Preview {
ContentView()
}
extension Color {
func luminance() -> Double {
// Convert SwiftUI Color to UIColor
let uiColor = UIColor(self)
// Extract RGB values
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
uiColor.getRed(&red, green: &green, blue: &blue, alpha: nil)
// Compute luminance.
return 0.2126 * Double(red) + 0.7152 * Double(green) + 0.0722 * Double(blue)
}
func isLight() -> Bool {
return luminance() > 0.5
}
func adaptedTextColor() -> Color {
return isLight() ? Color.black : Color.white
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment