I am making a color picker app in Swift and I need the text to adapt to the background color.
I have text on a UIView that is black by default and I would like it to turn lighter if there is a darker background color and to make the text darker if there is a lighter background color to make the text more readable.
Here are some screenshots:
Hardly readable text (First image)
Hardly readable text (Second image)
If it is possible I would be thankful for your reply.
Contrast with a White Background. Black text on a white background provides maximal value contrast and, therefore, optimal readability for body text. Black text on a white background provides maximal value contrast and, therefore, optimal readability for body text.
This is standardised by W3C's Web Content Accessibility Guidelines (WCAG) and decided based on the contrast ratio between colors, which you can calculate programmatically. In your case, you would want to use whichever of white or black has a higher contrast ratio with the background color.
There are two ways to use your custom colors in Swift UI. Select your object in device preview. Choose “Color” under the attributes inspector. Your custom colors now show at the bottom of the list!
You can do something like:
extension UIColor
{
var isDarkColor: Bool {
var r, g, b, a: CGFloat
(r, g, b, a) = (0, 0, 0, 0)
self.getRed(&r, green: &g, blue: &b, alpha: &a)
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
return lum < 0.50
}
}
Which will calculate the luminance of the color and determine if it's above a certain threshold. Then say myLabel.textColor = view.backgroundColor?.isDarkColor == true ? .white : .black
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With