调用的 API
SDL_INIT # 初始化 SDL 库
SDL_CreateWIndow # 创建窗口
SDL_CreateRenderer # 创建渲染器 需要指定渲染窗口
SDL_CreateTexture # 需要指定纹理的上下文 和 数据修改频率
SDL_UpdateTexuture # 把 cpu 数据拷贝到 gpu 纹理中
SDL_RenderClear # 清空窗口纹理
SDL_RenderCopy # 把更新后的纹理拷贝到窗口纹理上
SDL_RenderPresent # 渲染上屏 (清空和拷贝的窗口纹理都是 back纹理,需要 present 才能有效果)
具体代码
#include <iostream>
#include <SDL/SDL.h>
using namespace std;#pragma comment(lib, "SDL2.lib")
#undef main
int main(int argc, char* argv[])
{int w = 800;int h = 600;// 1 初始化if (SDL_Init(SDL_INIT_VIDEO)){cout << SDL_GetError() << endl;return -1;}// 2 生成 SDL 窗口auto screen = SDL_CreateWindow("teet sdl ffmpeg",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w, h,SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);if (!screen){cout << SDL_GetError() << endl;return -2;}// 3 渲染器auto render = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);if (!render){cout << SDL_GetError() << endl;return -3;}// 4 生成材质auto texture = SDL_CreateTexture(render, SDL_PIXELFORMAT_ARGB8888,SDL_TEXTUREACCESS_STREAMING,w, h);if (!texture){cout << SDL_GetError() << endl;return -4;}// 存放图像的数据shared_ptr<unsigned char> rgb(new unsigned char[w * h * 4]);auto d = rgb.get();char temp = 255;for (;;){temp--;// 判断退出SDL_Event ev;SDL_WaitEventTimeout(&ev, 10);if (ev.type == SDL_QUIT){SDL_DestroyWindow(screen);break;}for (int j = 0; j < h; j++){int b = j * w * 4;for (int i = 0; i < w * 4; i += 4){d[b + i] = 0; // Bd[b + i + 1] = 0; // Gd[b + i + 2] = temp; // Rd[b + i + 3] = 0; // A}}// 5 将内存数据写入材质SDL_UpdateTexture(texture, NULL, d, w * 4);// 6 清理屏幕SDL_RenderClear(render);SDL_Rect sdl_rect;sdl_rect.x = 0;sdl_rect.y = 0;sdl_rect.w = w;sdl_rect.h = h;// 7 复制材质到渲染器SDL_RenderCopy(render, texture,NULL,&sdl_rect);static bool flag = true;// 8 渲染if(flag)SDL_RenderPresent(render);}return 0;
}