Android Question Achieving a Contrast between Label Color and Label TextColor

Mahares

Expert
Licensed User
Longtime User
I use this code and it works in most cases for an xCLV items:
B4X:
lbldoctor.Color=Rnd(xui.Color_Black, xui.Color_White)
lbldoctor.textColor=Rnd(xui.Color_Black, xui.Color_White)
What is the best way to insure that there is always a contrast between the label color and its text color, so the text is always readable and visible. I do not want the label color to drown the text. Take a look at the forum avatars for instance. If the avatar is M, you will never see the same 2 avatars having the same colors and there is always a nice contrast between the label text color and the label background color. I like to achieve something like that.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Based on: https://stackoverflow.com/questions...lculate-the-contrast-ratio-between-two-colors
NC6Z7wtWP3.gif


B4X code:
B4X:
Sub Button1_Click
    Do While True
        Dim clr1 As Int = Rnd(xui.Color_Black, xui.Color_White)
        Dim clr2 As Int= Rnd(xui.Color_Black, xui.Color_White)
        If Contrast(clr1, clr2) > 4.5 Then Exit
    Loop
    Label1.TextColor = clr1
    Pane1.Color = clr2
    Log(Contrast(clr1, clr2))
End Sub

Private Sub Luminance (clr As Int) As Float
    Dim argb() As Int = GetARGB(clr)
    Dim a(3) As Float
    For i = 0 To 2
        Dim v As Float = argb(i + 1) / 255
        If v <= 0.03928 Then
            a(i) = v / 12.92
        Else
            a(i) = Power( (v + 0.055) / 1.055, 2.4)
        End If
    Next
    Return a(0) * 0.2126 + a(1) * 0.7152 + a(2) * 0.0722
End Sub

Private Sub Contrast(clr1 As Int, clr2 As Int) As Float
    Dim lum1 As Float = Luminance(clr1)
    Dim lum2 As Float = Luminance(clr2)
    Dim brightest As Float = Max(lum1, lum2)
    Dim darkest As Float = Min(lum1, lum2)
    Return (brightest + 0.05) / (darkest + 0.05)
End Sub

Sub GetARGB(Color As Int) As Int()
    Private 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
 
Upvote 0
Top