# pixel programming

This topic is 4912 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

After reading through a few tutorials on DX programming I commonly will see this statement: int index = i * lockedRect.Pitch / 4 + j this is usually used to reference individual pixels in the surface array. What I dont understnad is that why do you always divide by 4. I see that you have to index through the array using the i and j because its linear, im assuming that the lockedRect.Pitch is an offset but I dont see how this offset is working with the divison by 4. (Note: The pitch is given in Bytes) Also later in the code you will usually find the setting of the array to some hexidecimal color value, but the array your inputing the index into is pointed to by a DWORD pointer.

##### Share on other sites
If it is a 32 bit colour it will need 4 bytes per colour.

##### Share on other sites
I read into it a little bit more and I understand that pitch is actually the byte difference between start and end of pixels. So one question that remains is will you always divide by 4 when trying to set individual pixels on your screen or should it be by the bit depth?

##### Share on other sites
Supposedly pitch is the number of bytes in order to move up/down one row in a bitmap. For example, you might have a bitmap that's 201 pixels wide, using 24-bit color, so you'd have 603 bytes of color. But usually the stride will be multiples of 4 (or 8 or 16 depending on the situation), so your stride might be 604 bytes instead. That extra byte just isn't drawn on the screen.

I don't trust the multiple-of-four to always be the case. what I do (in C# for GDI+, at least) when I'm messing with 16-bit, 24-bit, 32-bit pixels:

int pixelsize = 3; // or 1, 2, 4.BitmapData bd = bmp.Lock(...);for (int y=0; y<height; ++y){  void *row = (uint*)(bd.Scan0.ToPointer() + y * bd.Stride);  for (int x=0; x<width*pixelsize; x+=pixelsize)  {    row[x] = whatever1;    row[x+1] = whatever2;    // etc, for however many bytes each pixel uses (1,2,3, or 4)  }}

Always make sure that you know what the bit depth is for the locked buffer that you get. (1 byte, 2 bytes, 3 bytes(in weird cases), or 4 bytes). Usually in game programming you'll just be using 4-byte RGBA.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 12
• 15
• 14
• 46
• 22
• ### Forum Statistics

• Total Topics
634055
• Total Posts
3015276
×