Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created May 20, 2024 21:36
Show Gist options
  • Save StewartLynch/40ad1186859b30584313fe10b9e193c4 to your computer and use it in GitHub Desktop.
Save StewartLynch/40ad1186859b30584313fe10b9e193c4 to your computer and use it in GitHub Desktop.
Adaptive Text Color Extension
import SwiftUI
extension Color {
// Credit for this goes to https://swiftandtips.com/adaptive-text-color-in-swiftui-based-on-background
// This is a slightly modified version to use Computed properties instead of functions
var luminance: Double {
// perceived brightness of a color 0...1
// 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 (take into account the sensitivity of color to the human eye.
// The higher the number, the lighter the color
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
}
var luminance2: Double? {
guard let components = UIColor(self).cgColor.components else { return nil }
return 0.2126 * components[0] + 0.7152 * components[1] + 0.0722 * components[2]
}
var adaptedTextColor: Color {
luminance > 0.5 ? Color.black : Color.white
}
var components: String {
guard let components = UIColor(self).cgColor.components else { return "" }
return "\(0.2126 * components[0]), \(0.7152 * components[1]), \(0.0722 * components[2])"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment