changing the color of a pixel in SDL

Started by
5 comments, last by Zahlman 14 years, 4 months ago
Hello everyone. I'm new to SDL and I have the following simpple question: How can I change the color of a pixel of a surface? I'm using these functions: Uint32 get_pixel( SDL_Surface* surface, int x, int y ) { Uint32 *pixels = (Uint32*)surface->pixels; return pixels[ ( y * surface->w ) + x ]; } void put_pixel( SDL_Surface *surface, int x, int y, Uint32 pixel ) { Uint32 *pixels = (Uint32 *)surface->pixels; pixels[ ( y * surface->w ) + x ] = pixel; } My problem is that get_pixel() gives a Uint32 and I don't know how to change for example the red value by 10. How can I convert it to something that I could handle? Thanks!
Advertisement
The Uint32 contains RGB (possibly alpha values too), each in 8 of the 32 bits. It usually looks like this: 0xXXRRGGBB. So to extract the color values you do the following:
red = (pixel >> 16) & 0xffgreen = (pixel >> 8) & 0xffblue = pixel & 0xff


Depending on the format of the back-buffer blue/red could be switched for example. Each color will be in the range [0, 255], and after you have modified the separate channels individually, you rebuild the pixel color with:
pixel = (red << 16) | (green << 8) | blue


Remember that red/green/blue have to stay in [0, 255].
Just a quick one, when doing that do you not have to consider the endianness of the system, or you could end up reading it backwards?
Game development blog and portfolio: http://gamexcore.co.uk
Yes, though all x86/x64 based systems have the same endianess. It could still be true though, as the backbuffer format can change. For example on a BGR format the B/R channels are switched compared to an RGB. And some application might have both ARGB and RGBA formats, though I'm not sure if they are both actually used.. at least DirectX only specifies one, though it's referred to both as RGBA (DX10) and ARGB (DX9). They both have the most significant byte as alpha (<< 24).
Perhaps SDL_MapRGB could be of use to you.

EDIT: The first parameter should be surface->format.
Thank you guys! so much!
[Never mind. Didn't notice that the OP wrote his own access functions. Doesn't SDL provide its own?]

This topic is closed to new replies.

Advertisement