0

Can someone help me to change the text color according to the background color like Microsoft One drive? in One drive for RGB(255,0,0) we are getting text color as black, but when using the below formulae we are getting text color as white.

public Color ContrastColor(Color iColor)
{
  // Calculate the perceptive luminance (aka luma) - human eye favors green color... 
  double luma = ((0.299 * iColor.R) + (0.587 * iColor.G) + (0.114 * iColor.B)) / 255;

  // Return black for bright colors, white for dark colors
  return luma > 0.5 ? Color.Black : Color.White;
}

1 Answers1

0

I'm not sure why you are dividing by 255 then checking for half. According to this answer, an undivided luma value of 150-186 should be sufficient.

Below is a browser based example, but it highlights the differences that you would get with your divisor approach for rgb(255,100,0) etc. It also shows that for rgb(255,0,0), you should be getting white really.

It might be worth logging your colours and luma values to check. or providing a java playground with some example data that doesn't do what you expect.

const getTextColour = (color) => {
  const luma = (color.r * 0.299) + (color.g * 0.587) + (color.b * 0.114)
  console.log('\ngetTextColour', JSON.stringify(color), luma)
  return luma > 186 ? 'black' : 'white' // Some people prefer 150
}
const getTextColourWithDivision = (color) => {
  const luma = ((color.r * 0.299) + (color.g * 0.587) + (color.b * 0.114)) / 255
  console.log('\ngetTextColourWithDivision', JSON.stringify(color), luma)
  return luma > 0.5 ? 'black' : 'white'
}

console.log(getTextColour({ r: 255, g: 0, b: 0 }))
console.log(getTextColourWithDivision({ r: 255, g: 0, b: 0 }))
console.log(getTextColour({ r: 255, g: 100, b: 0 }))
console.log(getTextColourWithDivision({ r: 255, g: 100, b: 0 }))
dangarfield
  • 2,210
  • 1
  • 13
  • 18