项目创建步骤
1. 使用Qt Creator创建一个C项目
2. 将SDL库文件放到源文件目录下
在项目pro文件中添加库文件
win32{INCLUDEPATH += $$PWD/SDL2-2.0.10/includeLIBS += $$PWD/SDL2-2.0.10/lib/x86/SDL2.lib
}
使用SDL创建一个窗口
#include <stdio.h>#include <SDL.h>#undef main // 先取消main函数(因为SDL内部使用了main函数)
int main()
{// 创建一个SDL_VIDEO窗口SDL_Window* window = NULL;SDL_Init(SDL_INIT_VIDEO);window = SDL_CreateWindow("Title",SDL_WINDOWPOS_UNDEFINED, // 默认x y 显示到窗口中间SDL_WINDOWPOS_UNDEFINED,640,480,SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);// 设置窗口属性if(!window){printf("Can't create window, err:%s\n", SDL_GetError());return 666;}SDL_Delay(5000); // 延迟5000msSDL_DestroyWindow(window); // 销毁窗口SDL_Quit(); // 释放资源return 0;
}
运行效果
SDL简单显示案例
#include <stdio.h>
#include <SDL.h>#undef main
int main()
{SDL_Window* window = NULL; // 窗口SDL_Renderer* renderer = NULL; // 渲染器SDL_Texture* texture = NULL; // 纹理SDL_Init(SDL_INIT_VIDEO);// 创建窗口window = SDL_CreateWindow("Window Title",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,640,480,SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);if(NULL == window){printf("Create Window error: %s\n", SDL_GetError());return -1;}// 创建渲染器(一个窗口可有多个渲染器)renderer = SDL_CreateRenderer(window, -1, 0);if(NULL == renderer){printf("Create Renderer error: %s\n", SDL_GetError());// 销毁窗口,释放资源SDL_DestroyWindow(window);SDL_Quit();return -1;}// 基于渲染器创建纹理texture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,640,480);if(NULL == texture){printf("Create Texture error: %s\n", SDL_GetError());// 销毁渲染器 窗口 释放资源SDL_DestroyRenderer(renderer);SDL_DestroyWindow(window);SDL_Quit();return -1;}int showCnt = 0; // 显示次数int run = 1; // 循环退出条件SDL_Rect rect; // 定义一个SDL矩形rect.w = 50;rect.h = 50;while(run){// 随机rect的位置rect.x = rand() % 600;rect.y = rand() % 400;// 设置渲染目标为纹理SDL_SetRenderTarget(renderer, texture);// 设置渲染绘制颜色SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255);// 刷新渲染SDL_RenderClear(renderer);// 设置渲染绘制颜色SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);// 绘制矩形SDL_RenderDrawRect(renderer, &rect);// 绘制填充矩形SDL_RenderFillRect(renderer, &rect);// 恢复渲染目标为窗口SDL_SetRenderTarget(renderer, NULL);SDL_RenderCopy(renderer, texture, NULL, NULL);// 显示纹理SDL_RenderPresent(renderer);SDL_Delay(300);if(showCnt++ >= 30)run = 0;}// 销毁 纹理 渲染器 窗口,释放资源SDL_DestroyTexture(texture);SDL_DestroyRenderer(renderer);SDL_DestroyWindow(window);SDL_Quit();return 0;
}