# SDL2Demo **Repository Path**: naka507/sdl2-demo ## Basic Information - **Project Name**: SDL2Demo - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2023-12-14 - **Last Updated**: 2024-03-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SDL2Demo cmake .. -G "MinGW Makefiles" cmake -G "Visual Studio 17 2022" -T host=x86 ## SDL 核心 API 使用流程 1. 初始化:SDL_Init() 2. 创建SDL_Window:SDL_CreateWindow() 3. 创建SDL_Render:SDL_CreateRenderer() 4. 创建SDL_Texture:SDL_CreateTexture() 5. 更新SDL_Texture:SDL_UpdateTexture() 6. 渲染SDL_Texture:SDL_RenderCopy() 7. 显示:SDL_RenderPresent() 8. 返回步骤4继续执行 ### 设置画笔的颜色 ```c int SDL_SetRenderDrawColor(SDL_Renderer* renderer, // 渲染器 Uint8 r, // 红 Uint8 g, // 绿 Uint8 b, // 蓝 Uint8 a) // 透明值 ``` ### 绘制一个点 ```c int SDL_RenderDrawPoint(SDL_Renderer* renderer, int x, int y) ``` ### 绘制多个点 ```c int SDL_RenderDrawPoints(SDL_Renderer* renderer, const SDL_Point* points, int count) ``` ### 绘制直线 ```c int SDL_RenderDrawLine(SDL_Renderer* renderer, // 渲染器 int x1, // 端点1的x坐标 int y1, // 端点1的y坐标 int x2, // 端点2的x坐标 int y2) // 端点2的y坐标 ``` ### 绘制多条线 ```c int SDL_RenderDrawLines(SDL_Renderer* renderer, const SDL_Point* points, int count) ``` ### 绘制矩形 ```c int SDL_RenderDrawRect(SDL_Renderer* renderer, const SDL_Rect* rect) ``` ### 填充矩形 ```c int SDL_RenderFillRect(SDL_Renderer* renderer, const SDL_Rect* rect) ``` ### 填充多块矩形 ```c int SDL_RenderDrawRects(SDL_Renderer* renderer, const SDL_Rect* rects, int count) ``` ### 操作事件队列 * SDL_PollEvent: 将队列头中的事件抛出来。 * SDL_WaitEvent: 当队列中有事件时,抛出事件。否则处于阻塞状态,释放 CPU。 * SDL_WaitEventTimeout: 与SDL_WaitEvent的区别时,当到达超时时间后,退出阻塞状态。 * SDL_PeekEvent: 从队列中取出事件,但该事件不从队列中删除。 * SDL_PushEvent: 向队列中插入事件。 ### 处理事件 * SDL_WindowEvent : Window窗口相关的事件。 * SDL_KeyboardEvent : 键盘相关的事件。 * SDL_MouseMotionEvent : 鼠标移动相关的事件。 * SDL_QuitEvent : 退出事件。 * SDL_UserEvent : 用户自定义事件。 ### SDL_WaitEvent和SDL_PollEvent使用的场景不同: * 对于游戏来说,它要求事件的实时处理,我们最好使用SDL_PollEvent方法 * 对于一些其它实时性不高的case来说,则可以使用 SDL_WaitEvent了 ### 渲染纹理 ```c //创建 SDL_Texture* SDL_CreateTexture(SDL_Renderer* renderer, // 渲染器 Uint32 format, // 渲染数据的格式,如YUV、RGB int access, // Texture 类型,target、stream int w, int h) //渲染 int SDL_RenderCopy(SDL_Renderer* renderer, SDL_Texture* texture, const SDL_Rect* srcrect, const SDL_Rect* dstrect) //销毁 void SDL_DestroyTexture(SDL_Texture* texture) ``` ### 帧速 > 很多人都在SDL_PollEvent和SDL_WaitEvent之间纠结。 > 前者会带来更好的帧数表现,但是CPU占用极大,可以直接吃掉一个核心。后者则基本不占用CPU,但是帧数会受到影响。 > 有没有办法使两者的优势结合呢?其实只要用轮询(SDL_PollEvent)并且配合一个帧速限制即可。 > 什么是帧速(FPS)?是指画面每秒传输帧数。要保证画面流畅,一般就要保持帧速在20及以上。要想限制帧速,我们只要在循环中加入如下代码: ```c const Uint FPS=1000/20;//20可替换为限制的帧速 Uint32 _FPS_Timer; while (quit!=0){ //事件处理等 if(SDL_GetTicks()-_FPS_Timer