Today, I would like to share a function that has been very useful to me. Sometimes, when dealing with a dynamic background in our applications, we may encounter problems with text legibility due to improper color combinations.
When the background is dynamic, it can be either dark with dark text or light with light text, making it difficult for the user to read.
💡 To solve this problem, I developed a function that determines whether the background is dark or light, returning a boolean indicating this.
The first step is to analyze the hexadecimal color code and convert it to RGB. We can do this using the following function:
int r = int.parse(hexColor.substring(0, 2), radix: 16);
int g = int.parse(hexColor.substring(2, 4), radix: 16);
int b = int.parse(hexColor.substring(4, 6), radix: 16);
Where the parameter radix: 16 specifies that we are using base 16 (hexadecimal) for the conversion. Next, we must calculate the luminance of the color.
The formula will return a value between 0 and 1, where 0 indicates a darker color and 1 a lighter color:
double luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
🎨 The luminance of a color is based on the relative contribution of each component to the perceived brightness. Each component (red, green, and blue) is multiplied by its corresponding coefficient (0.2126, 0.7152, and 0.0722 respectively), representing its relative contribution to the total luminance.
💻 Finally, the function is defined as follows:
bool isDarkBackground(String hexColor) {
hexColor = hexColor.replaceAll('#', '');
int r = int.parse(hexColor.substring(0, 2), radix: 16);
int g = int.parse(hexColor.substring(2, 4), radix: 16);
int b = int.parse(hexColor.substring(4, 6), radix: 16);
double luminancia = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
if (luminancia < 0.5) {
return true;
} else {
return false;
}
}
📹 Check out the video demonstrating the implementation of this function.
I hope this function is very useful for you. If you have any questions or need more information, just leave a comment.
Let's code with FLOW! 🎉