Skip to content

Instantly share code, notes, and snippets.

@mariosaputra
Created April 21, 2024 04:50
Show Gist options
  • Save mariosaputra/fa2376f8d3bbfd87ea8e21289c8ec1f8 to your computer and use it in GitHub Desktop.
Save mariosaputra/fa2376f8d3bbfd87ea8e21289c8ec1f8 to your computer and use it in GitHub Desktop.
Dynamic Foreground Color
import Foundation
import SwiftUI
import UIKit
extension Color {
func brightness() -> Double {
// Assuming the color is RGB
let components = UIColor(self).cgColor.components!
return 0.299 * components[0] + 0.587 * components[1] + 0.114 * components[2] // Standard formula for brightness
}
func appropriateForegroundColor(forBackgroundColor backgroundColor: Color) -> Color {
return backgroundColor.brightness() < 0.5 ? .white : .black
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment