Question

We generally write 143.0/255.0 in UIColor setcolor RGB arguements . Can anybody pl tel me the logic behind Dividing by 255.0 . I have some knowledge but i guess it is incomplete.

Was it helpful?

Solution

Most Core Graphic APIs expect the RGB color components to be in the range of 0.0 to 1.0. However many computer color palettes and Mac output devices expect RGB color components to be representable in 8 bit values, which, when expressed as integers, are in the range of 0 to 255.

If you are looking up a color from a table with 8-bit component values (e.g. a web color of #RRGGBB), then you need to scale the values from the range 0 to 255 to the range 0 to 1.0, which is done by dividing by 255.0f (in floating point, so you don't end up truncating to 0).

OTHER TIPS

You are diving by 255.0 for 2 reasons

  1. You need a decimal that represents the percentage of that channel in the range 0-1
  2. If you did 143/255 it would be integer division, which would give an integer result

This is because most people are accustomed to defining colors on a scale from 0-255. Because the parameter demand arguments to reperest color from 0-1, the /255.0 is needed. You could just as easily specify something like 0.5 to mean 128.0/255.0.

Note that this question is about color reperesentation and inspecific to iPhone.

UIColor doesn't have methods to create color Objects out the 0-255 rgb ranges people are used to (mostly from webdesign).

UIColor's easiest initializer for rgb colors use a 0.0 - 1.0 color range for each channel.

So, if you have a a 0 - 255 based color value, dividing it with 255.0 gives you a value between 0.0 and 1.0:

255.0 / 255.0 = 1.0

0.0 / 255.0 = 0.0

It's just the easiest way to convert them non-destructive, so you can adjust the 255-based values without recalculate the values everytime by yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top