简体   繁体   中英

SDL2 modifying pixels

I want to modify single pixels with SDL2 and I don't want to do it with surfaces.

Here is the relevant part of my code:

// Create a texture for drawing
SDL_Texture *m_pDrawing = SDL_CreateTexture(m_pRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, 1024, 768);

// Create a pixelbuffer
Uint32 *m_pPixels = (Uint32 *) malloc(1024*768*sizeof(Uint32));

// Set a single pixel to red
m_pPixels[1600] = 0xFF0000FF;

// Update the texture with created pixelbuffer
SDL_UpdateTexture(m_pDrawing, NULL, m_pPixels, 1024*sizeof(Uint32));

// Copy texture to render target
SDL_RenderCopy(m_pRenderer, m_pDrawing, NULL, NULL);

If it is rendered then with SDL_RenderPresent(m_pRenderer) nothing appears on screen. Here they explained that you could either use "surface->pixels, or a malloc()'d buffer". So, what's wrong?

Edit: In the end it was just my m_pRenderer which was defined after the SDL_CreateTexture call. Everything works fine now and I fixed the small bug in the buffer allocation, so this code should be working.

I'm not sure if this is your problem, but it's a bug:

Uint32 *m_pPixels = (Uint32 *) malloc(1024*768);

You need a * sizeof(Uint32) in there, if you want to allocate enough data to represent the pixels in your surface:

Uint32 *m_pPixels = (Uint32 *) malloc(1024*768*sizeof(Uint32));

(And if this is C, you don't need the cast.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM