Thyago B. Rodrigues
Thyago B. Rodrigues

Reputation: 630

Coloring RGB pixels in Java

guys.

I've been studying some code, and it involves painting pixels. I came accross the following piece of code:

pixels[x + y * width] =  i * 128;

What I can't seem to understand is: when i is odd, the pixels are drawn in blue; when i is even, they're drawn in black. I've read about the rgb = 65536 * r + 256 * g + b, but I failed to fit this problem into this logic. For example, why would 2688 (21 * 128) and 2816 (23 * 128) draw blue pixels while 2816 (22 * 128) draws blacks?

Thanks for any help.

Upvotes: 0

Views: 144

Answers (2)

Daniel Walton
Daniel Walton

Reputation: 228

The blue value is 0 to 255, once you go above 255 you start setting the green. the rgb values are bytes encoded in an integer so the integer has the first byte unused, the second byte is red, the third green and the fourth blue. you may find it easier to shift byte values rather than multiply numbers to move them up the bytes.

Upvotes: 0

rgettman
rgettman

Reputation: 178263

i * 128 modulo 256 is the blue value. If i is odd, then i * 128 modulo 256 is 128, a medium blue. If i is even, then i * 128 modulo 256 is 0, no blue component. The green component here is 10 if i is 21 (i * 128 / 256), and 11 if i is 22 or 23 and is almost black. The result values here are not high enough to "spill over" and create a red component; it's 0 here for i values of 21 or 23.

Upvotes: 3

Related Questions