Skip to content

Instantly share code, notes, and snippets.

@cynthia2006
Created August 31, 2023 17:37
Show Gist options
  • Save cynthia2006/3cf9e3a16ceea48e3674f98597b57a0f to your computer and use it in GitHub Desktop.
Save cynthia2006/3cf9e3a16ceea48e3674f98597b57a0f to your computer and use it in GitHub Desktop.
Simple SDL2 program to draw lines (left-click and drag to draw lines, right to erase)
#include <SDL2/SDL.h>
#include <stdbool.h>
struct pt_pair {
SDL_Point begin;
SDL_Point end;
};
int main() {
SDL_Init(SDL_INIT_AUDIO);
SDL_Window *w;
SDL_Renderer *r;
SDL_CreateWindowAndRenderer(800, 600, 0, &w, &r);
SDL_Event e;
struct pt_pair *pt_pairs = NULL;
int n_pts = 0;
SDL_Point begin = {0};
SDL_Point end = {0};
bool dragging = 0;
bool running = 1;
while (running) {
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_KEYDOWN:
switch (e.key.keysym.sym) {
case SDLK_ESCAPE:
running = false;
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
if (e.button.button == SDL_BUTTON_LEFT)
{
dragging = 1;
begin.x = end.x = e.button.x;
begin.y = end.y = e.button.y;
}
break;
case SDL_MOUSEBUTTONUP:
if (e.button.button == SDL_BUTTON_LEFT) {
dragging = 0;
pt_pairs = realloc(pt_pairs, sizeof(struct pt_pair) * (n_pts + 1));
pt_pairs[n_pts].begin = begin;
pt_pairs[n_pts].end = end;
++n_pts;
} else if (e.button.button == SDL_BUTTON_RIGHT) {
n_pts = 0;
// free(pt_pairs);
}
break;
case SDL_MOUSEMOTION:
if (dragging)
{
end.x = e.motion.x;
end.y = e.motion.y;
}
break;
case SDL_QUIT:
running = false;
break;
}
}
SDL_SetRenderDrawColor(r, 0x0, 0x0, 0x0, 0xFF);
SDL_RenderClear(r);
SDL_SetRenderDrawColor(r, 0xFF, 0xFF, 0xFF, 0xFF);
for (int i = 0; i < n_pts; ++i) {
struct pt_pair pair = pt_pairs[i];
SDL_RenderDrawLine(r, pair.begin.x, pair.begin.y, pair.end.x, pair.end.y);
}
if (dragging)
SDL_RenderDrawLine(r, begin.x, begin.y, end.x, end.y);
SDL_RenderPresent(r);
}
SDL_DestroyRenderer(r);
SDL_DestroyWindow(w);
SDL_Quit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment