Advertisement
j0h

SDL2drawPixles

j0h
Jul 31st, 2022 (edited)
1,363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <SDL2/SDL.h>
  3. //Source: https://bitbucket.org/dandago/gigilabs/src/master/Sdl2PixelDrawing/Sdl2PixelDrawing/main.cpp
  4. //Define window height, width
  5. #define height 1280
  6. #define width   760
  7. int main(int argc, char ** argv){
  8.     bool leftMouseButtonDown = false;
  9.     bool quit = false;
  10.     SDL_Event event;
  11.     SDL_Init(SDL_INIT_VIDEO);
  12.     SDL_Window * window = SDL_CreateWindow("SDL2 Pixel Drawing",  SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, height, width, SDL_WINDOW_FULLSCREEN);
  13.  
  14.     SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
  15.     SDL_Texture * texture = SDL_CreateTexture(renderer,  SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, height, width);
  16.     Uint32 * pixels = new Uint32[height * width];
  17.     SDL_SetRenderDrawColor(renderer, 255, 128, 255, 255); //has no effect
  18.  
  19.  
  20.     memset(pixels, 255, height * width * sizeof(Uint32)); //int is bg color
  21.  
  22.     while (!quit){
  23.         SDL_UpdateTexture(texture, NULL, pixels, height * sizeof(Uint32));
  24.         SDL_WaitEvent(&event);
  25.  
  26.         switch (event.type){
  27.             case SDL_QUIT:
  28.                 quit = true;
  29.                 break;
  30.             case SDL_MOUSEBUTTONUP:
  31.                 if (event.button.button == SDL_BUTTON_LEFT)
  32.                     leftMouseButtonDown = false;
  33.                 break;
  34.             case SDL_MOUSEBUTTONDOWN:
  35.                 if (event.button.button == SDL_BUTTON_LEFT)
  36.                     leftMouseButtonDown = true;
  37.             case SDL_MOUSEMOTION:
  38.                 if (leftMouseButtonDown){
  39.                     int mouseX = event.motion.x;
  40.                     int mouseY = event.motion.y;
  41.                    
  42.                     pixels[mouseY * height+ mouseX] = 0;
  43.                 }
  44.                 break;
  45.         }
  46.         SDL_RenderClear(renderer);
  47.         SDL_RenderCopy(renderer, texture, NULL, NULL);
  48.         SDL_RenderPresent(renderer);
  49.     }
  50.  
  51.     delete[] pixels;
  52.     SDL_DestroyTexture(texture);
  53.     SDL_DestroyRenderer(renderer);
  54.  
  55.     SDL_DestroyWindow(window);
  56.     SDL_Quit();
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement