Android Code Snippet [B4X] Check if color is dark or light

This Code is a convert from this Stackoverflow thread.

B4X:
Private Sub isColorDark(color As Int) As Boolean
    
    Dim darkness As Int = 1 - (0.299 * GetARGB(color)(1) + 0.587 * GetARGB(color)(2) + 0.114 * GetARGB(color)(3))/255
    
    If darkness <= 0.5 Then
        Return    False 'It's a light color
    Else
        Return    True 'It's a dark color
    End If
    
End Sub

Sub GetARGB(Color As Int) As Int()
    Dim res(4) As Int
    res(0) = Bit.UnsignedShiftRight(Bit.And(Color, 0xff000000), 24)
    res(1) = Bit.UnsignedShiftRight(Bit.And(Color, 0xff0000), 16)
    res(2) = Bit.UnsignedShiftRight(Bit.And(Color, 0xff00), 8)
    res(3) = Bit.And(Color, 0xff)
    Return res
End Sub

B4X:
public boolean isColorDark(int color){
    double darkness = 1-(0.299*Color.red(color) + 0.587*Color.green(color) + 0.114*Color.blue(color))/255;
    if(darkness<0.5){
        return false; // It's a light color
    }else{
        return true; // It's a dark color
    }
}
 

klaus

Expert
Licensed User
Longtime User
I use this routine to get a contrast color.
It is the same equation, but only with Int values.

B4X:
'returns white for a dark color or returns black for a light color for a good contrast between background and text colors
Private Sub GetContrastColor(Color As Int) As Int
    Private a, r, g, b, yiq As Int    'ignore
    
    a = Bit.UnsignedShiftRight(Bit.And(Color, 0xff000000), 24)
    r = Bit.UnsignedShiftRight(Bit.And(Color, 0xff0000), 16)
    g = Bit.UnsignedShiftRight(Bit.And(Color, 0xff00), 8)
    b = Bit.And(Color, 0xff)
    
    yiq = r * 0.299 + g * 0.587 + b * 0.114
    
    If yiq > 128 Then
        Return xui.Color_Black
    Else
        Return xui.Color_White
    End If
End Sub
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…