Skip to content

Color.AdjustForContrast gives up on mid-tone backgrounds (luminance ~0.18-0.5) because it always lightens there, even when darkening would pass #279

Description

@matt-edmondson

What's wrong

Color.AdjustForContrast (Semantics.Color/Color.Operations.cs:52-99) decides which way to move with bool goLighter = background.RelativeLuminance < 0.5; (line ~62). It then binary-searches only in that direction. If the target is still not met, it returns this unchanged (line ~95).

The 0.5 threshold is not where lightening and darkening give equal contrast. WCAG contrast is (Lmax+0.05)/(Lmin+0.05). White against a background of luminance Lb gives 1.05/(Lb+0.05), and black gives (Lb+0.05)/0.05. The two are equal at Lb ≈ 0.179. For any background with relative luminance between about 0.18 and 0.5, the method picks the direction with the lower achievable contrast.

Above Lb ≈ 0.183, white cannot reach AA (4.5:1). Above Lb ≈ 0.30, it cannot reach even large-text AA (3:1). In those ranges the method returns the original failing color, even though darkening would meet the target easily. The doc comment says it returns the input unchanged "if no adjustment can reach the target", which is not the case here.

Failure scenario

  • Background: sRGB (0.58, 0.58, 0.58), relative luminance 0.296.
  • Foreground: sRGB (0.55, 0.55, 0.55), relative luminance 0.263, contrast 1.10.
  • Call: fg.AdjustForContrast(bg, AccessibilityLevel.AA).
  • Result: the unchanged foreground, still at contrast 1.10.
  • Pure black against the same background gives 6.91:1, so darkening would have met AA.

Any mid-grey or mid-tone UI background (roughly #767676 to #BCBCBC) is affected.

Suggested fix

Pick the direction whose extreme gives the higher achievable contrast, e.g. goLighter = (1.05 / (bgLum + 0.05)) >= ((bgLum + 0.05) / 0.05) (equivalently bgLum < ~0.179). More robust: try the preferred direction first and fall back to the other when the first cannot reach required. Add a test with a mid-luminance background (around 0.3).

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions