How to render a rectangle SDL2 texture from a buffer of hex values?

How to render a rectangle SDL2 texture from a buffer of hex values?



I'm having some trouble understanding texture streaming and loading a 2D texture from an array of raw pixel data.



Here is my code:


#include <stdio.h>
#include <stdlib.h>

#include <SDL2/SDL.h>

#define WINDOW_W 640
#define WINDOW_H 320

int main(int argc, char *argv)
SDL_RENDERER_PRESENTVSYNC
);
if (renderer == NULL)
exit(3);

SDL_Event ev;
int window_running = 1;

SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, 64, 32);
Uint32 pixels[64 * 32];
for (int i = 0; i < (64 * 32); i++)
pixels[i] = 0xFF00FFFF;
for (int i = 0; i < 64; i++)
pixels[i] = 0xFF0000FF;
SDL_UpdateTexture(texture, NULL, pixels, 4);

while (window_running)

while (SDL_PollEvent(&ev) != 0)

if (ev.type == SDL_QUIT)
window_running = 0;

SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);


SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

return 0;



Instead of my program drawing the first 64 pixels red and the rest magenta, it just spits out a random chunk of red and yellow pixels.



I'm having trouble understanding SDL_CreateTexture and SDL_UpdateTexture.





post a screenshot pls
– xaxxon
Aug 27 at 1:23





because the code you posted seems good to me: i.imgur.com/tg6Z38v.png
– xaxxon
Aug 27 at 1:39




1 Answer
1



Your pitch in UpdateTexture is wrong. Pitch is byte length of a row, not single pixel. In your case pitch is 64*4.


pitch


64*4



Pixel format SDL_PIXELFORMAT_RGBA32 is alias to either SDL_PIXELFORMAT_RGBA8888 or SDL_PIXELFORMAT_ABGR8888 (latter in your case). Look at https://wiki.libsdl.org/SDL_PixelFormatEnum . So your 0xFF00FFFF is yellow (R=0xff, G=0xff, B=0, A=0xff).


SDL_PIXELFORMAT_RGBA32


SDL_PIXELFORMAT_RGBA8888


SDL_PIXELFORMAT_ABGR8888


0xFF00FFFF



Finally, if we're talking about texture streaming (i.e. updating every frame or otherwise very often), you should create streaming texture and use LockTexture/UnlockTexture. UpdateTexture is for static textures.





Thank you so much! The 'pitch' variable solved it! That was the only part I didn't quite understand and now its working exactly as I wanted!
– Conner Turmon
Aug 27 at 20:33






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)