Created
April 21, 2024 04:50
-
-
Save mariosaputra/fa2376f8d3bbfd87ea8e21289c8ec1f8 to your computer and use it in GitHub Desktop.
Dynamic Foreground Color
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 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