How does one draw with pixels in SDL2.0?
I'm trying to get familiar with C++, but this is very difficult to do without pretty pictures, so I'm trying to get a very basic graphics display thing running. All I really want it to do is give me a window, let me draw rgbα pixels on it, and access information about those pixels. There may be other things I want that I'm not aware of, but that's all that's on my list right now. My research on this has lead me to try using SDL, the current version being 2.0.
Almost all my graphics experience comes from using JavaScript on a <canvas>
. Most of the other bit comes from my calculator, which has this really awesome Pxl-On()
command, so easy.
I'm using MinGW for my C++, if it matters. Also, if there's something better** out there than SDL2.0 for what I need, advice welcome.
** "better" means "contains what functionality I need, but less total functionality than SDL2.0, and/or has a more intuitive/less complex*** API than SDL2.0."
*** Less lines of code to accomplish the same task.
Runnable example
Draws a diagonal red line pixel by pixel on the screen using SDL_RenderDrawPoint
.
main.c
#include <stdlib.h>
#include <SDL2/SDL.h>
#define WINDOW_WIDTH 600
int main(void) {
SDL_Event event;
SDL_Renderer *renderer;
SDL_Window *window;
int i;
SDL_Init(SDL_INIT_VIDEO);
SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_WIDTH, 0, &window, &renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
for (i = 0; i < WINDOW_WIDTH; ++i)
SDL_RenderDrawPoint(renderer, i, i);
SDL_RenderPresent(renderer);
while (1) {
if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
break;
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
Compile and run:
gcc -std=c89 -Wextra -pedantic-errors -o main.out main.c -lSDL2
./main.out
If you want to set a large rectangle of pixels at once, e.g. the entire screen or a sprite, use SDL_Texture
+ SDL_RenderCopy
and possibly SDL_TEXTUREACCESS_STREAMING
, as that will be much faster. Examples at:
Tested on libsdl 2.0.2, Ubuntu 15.10.