Search code examples
pythoncolorskivy

What are Kivy color codes and how do they work?


I can't find this question anywhere so...

What are kivy color codes ( like the ones with 4 numbers)

example

Window.clearcolor = (1, 1, 1, 1)

I know I can just easily use RGB with a few lines of code, but I really just curious on what this type of color system is and how it works.


Solution

  • Kivy's colours are RGB(A) - don't confuse the colour space with the in-memory representation of the colour.

    Ultimately RGB measures each of the red, green and blue colour components on the scale from lightness zero (black) to maximum lightness (pure red/blue/green, if you like). Mathematically, this is a continuous interval consisting of infinite lightness choices, but in practice you can't represent all of those so you have to pick whatever is useful.

    RGB colour codes with each component in the range 0-255 are often used because they map well to physical devices. For instance, each pixel of your monitor probably supports 255 (not-coincidentally 2^8 - 1) settings for each colour, so if you want to write code to directly address these it's natural to use an integer in this range: in this case 255 represents maximum lightness.

    However, the choice of 255 here is quite arbitrary an exposes an implementation detail of the colour handling. It's especially arbitrary if you want to represent continuous colour intervals in which you do colour transformations. For instance, if rendering a complex scene you could imagine complex lighting transformations where lights bounce off surfaces (getting darker if not 100% reflective), or combine where two lights shine in the same place. If you clipped the values to 255 integers at every step the result would look rubbish as it totally fails to represent the continuous spectrum the light has passed through. In a case like this it makes much more sense to use a data type representing something as close as possible to a continuous interval: floats in the range 0-1 are the obvious choice, with 1 representing maximum lightness.

    You might consider that this is also more mathematically pure, avoiding unnecessarily exposing an implementation detail of how the colours are stored, although there is some value in directly controlling pixel colours.

    This is also why you can convert to Kivy's convention by dividing the 0-255 values by 255: they represent exactly the same thing.

    In any case, the 0-1 range is standard in e.g. OpenGL for this reason. Kivy chooses this convention, rather than the 0-255 one.