OT: Type on Background - Contrast Ratios

hh hh at hyperhh.de
Fri Oct 7 11:47:43 EDT 2016


Below are two functions on base of the ones mentioned in the
W3C's Accessibility Recommendations. They work fine here for me.

To test these, I made a stack for the Raspi collection in the forum.
This stack contains also a _simple_ algorithm for _trying_ to get a
textColor on base of the current textColor (the current backColor
is fixed) such that a contrast ratio of at least 7 is reached.
Works for giving an "advice" in most cases I tried. The algorithm
may easily be improved (for example by giving the change of color
channels different weights, adaptive, on base of input). 

-- usage example
on mouseUp
  lock screen; lock messages
  put the backColor of fld "Text" into bC
  put the backColor of fld "Text" into fC
  put relativeLuminance(bC) into bL
  put relativeLuminance(fC) into fL
  put contrastRatio(bL,fL) into contrastBF
  put "Contrast Ratio: " & round(contrastBF,2) into fld "contrastRatio"
  unlock screen; unlock messages
end mouseUp

-- param RGB is of the form "r,g,b" where each 
-- item r,g,b is an integer in range 0-255
function relativeLuminance RGB
  put 0 into tLuminance
  put "0.2126,0.7152,0.0722" into tWeights
  repeat with i=1 to 3
    put item i of RGB into ci
    put ci/255 into cc
    if cc <= 0.03928 then
      put cc/12.92 into ri
    else
      put ((cc+0.055)/1.055)^2.4 into ri
    end if
    add (item i of tWeights*ri) to tLuminance
  end repeat
  return tLuminance
end relativeLuminance

-- computes ratio of lighter against darker r.L.
function contrastRatio lu1,lu2
  if lu1 > lu2 then -- lu2 is darker
    return (lu1 + 0.05) / (lu2 + 0.05)
  else return (lu2 + 0.05) / (lu1 + 0.05)
end contrastRatio





More information about the use-livecode mailing list