主要是利用SDL_CreateWindowFrom函数,所以要求SDL2.0
方法/步骤 官方下载SDL2.0开发包 使用VC向导工具,新建 Window 32工程,在此工程示例名为SDLWin32 设置工程属性,添加对应头文件和库文件 在工程源文件SDLWin32.cpp中添加SDL 头文件和库文件 #include <SDL.h> #pragma comment (lib,"SDL2.lib") 添加变量: SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *sprite; int window_w, window_h; int sprite_w, sprite_h; SDL_Event event; 添加函数LoadSprite,目的用来加载纹理图片。 SDL_Texture * LoadSprite(SDL_Renderer *renderer, char *file) { SDL_Surface *temp; SDL_Texture *sprite; /* Load the sprite image */ temp = SDL_LoadBMP(file); /* Set transparent pixel as the pixel at (0,0) */ if (temp->format->palette) { SDL_SetColorKey(temp, 1, *(Uint8 *) temp->pixels); } /* Create textures from the image */ sprite = SDL_CreateTextureFromSurface(renderer, temp); if (!sprite) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError()); SDL_FreeSurface(temp); return 0; } SDL_FreeSurface(temp); /* We're ready to roll. :) */ return sprite; } 添加绘图函数 Draw,该函数目的用来将加载的图片纹理显示,背景为纯黑色。 void Draw(SDL_Renderer * renderer, SDL_Texture * sprite) { SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, sprite, NULL, NULL); SDL_RenderPresent(renderer); } 在WinMain函数首行加入SDL库初始化函数。 SDL_VideoInit(NULL); 并替换消息循环函数为: int done = 0; while (!done) { /* Check for events */ while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_EXPOSED: SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer); break; } break; case SDL_QUIT: done = 1; break; default: break; } } Draw(renderer, sprite); } 在WndProc函数中添加WM_CREATE消息,并添加以下代码,目的是将当前窗口设置为引擎渲染窗口,并设置标题,加载图片纹理。 case WM_CREATE: window=SDL_CreateWindowFrom(hWnd); SDL_SetWindowTitle(window, "SDL Native Window Test"); renderer = SDL_CreateRenderer(window, -1, 0); SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); sprite = LoadSprite(renderer, "flower.bmp"); break; 同时修改WM_DESTROY消息,释放资源,否则会出现内存泄露。 case WM_DESTROY: SDL_VideoQuit(); PostQuitMessage(0); exit(0); break; 按F7编译程序,在生成目录加入SDL2.dll文件,并将实现准备好的flower.bmp文件放到程序所在文件夹下,双击exe程序,即可查看运行结果。