Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining text color from the background color in Swift?

Tags:

ios

swift

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)
img

Hardly readable text (Second image)
img

If it is possible I would be thankful for your reply.

like image 236
Oli C Avatar asked Nov 18 '17 11:11

Oli C


People also ask

How do you select background color for text?

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.

How do we figure out if white color font or black color font is more readable?

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.

How do I see custom colors in Swift?

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!


1 Answers

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

like image 82
beyowulf Avatar answered Sep 30 '22 05:09

beyowulf