渲染第一个 SDL 窗口
首先我们从一个简单的例子讲起,我们渲染一个绿色背景的窗口。
基本步骤就是创建窗口和渲染器,然后在循环中不断的渲染窗口并展示。
SDL_Init,SDL_CreateWindow 和 SDL_CreateRenderer 拥有 bool 类型的返回值,下列代码中省略了返回值判断。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #include <SDL3/SDL.h>
int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("Hello World", 800, 600, 0); SDL_Renderer* renderer = SDL_CreateRenderer(window, nullptr);
SDL_Event e; bool quit = false; while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_EVENT_QUIT) { quit = true; } }
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); }
SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
|
更加的模块化 SDL3
SDL3 中只需要 #define SDL_MAIN_USE_CALLBACKS 1 并 #include <SDL3/SDL_main.h> 即可使用回调函数代替 main 函数,从而更加方便的编写程序。
最关键的四个回调函数为:
- 程序启动时执行:
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]);
- 有新事件时执行:
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event);
- 程序每帧都执行:
SDL_AppResult SDL_AppIterate(void *appstate);
- 程序退出时执行:
void SDL_AppQuit(void *appstate, SDL_AppResult result);
具体代码结构如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #define SDL_MAIN_USE_CALLBACKS 1 #include <SDL3/SDL.h> #include <SDL3/SDL_main.h> #include <iostream>
static SDL_Window *window = nullptr; static SDL_Renderer *renderer = nullptr;
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Hello World", 800, 600, 0); renderer = SDL_CreateRenderer(window, nullptr);
return SDL_APP_CONTINUE; }
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { if (event->type == SDL_EVENT_QUIT) { return SDL_APP_SUCCESS; }
return SDL_APP_CONTINUE; }
SDL_AppResult SDL_AppIterate(void *appstate) { SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer);
return SDL_APP_CONTINUE; }
void SDL_AppQuit(void *appstate, SDL_AppResult result) { std::cerr << "SDL_AppQuit." << std::endl; }
|