基于渲染器 显示bmp图片
-
- 初始化SDL SDL_Init
-
- 创建窗口 SDL_CreateWindow
-
- 基于窗口创建渲染器 SDL_CreateRenderer
-
- 加载bmp图片到surface SDL_LoadBMP
-
- 根据图片surface创建纹理 SDL_CreateTextureFromSurface
-
- 绘制三部曲
清空渲染器上一次显示 SDL_RenderClear
拷贝纹理数据到渲染器 SDL_RenderCopy
更新渲染器显示 SDL_RenderPresent -
- 释放资源,退出 SDL_FreeSurface......
#include <iostream>
/* 纹理和渲染(渲染显示bmp图片) */
extern "C"
{
#include <SDL.h>
}
#pragma comment(lib, "SDL2.lib")
#undef main
int main()
{
// 1. 初始化
int nRet = SDL_Init(SDL_INIT_EVERYTHING);
if (nRet < 0)
{
std::cout << "SDL Error: " << SDL_GetError() << std::endl;
return -1;
}
// 2. 创建窗口
SDL_Window* pWnd = SDL_CreateWindow("Title",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
640, 480,
SDL_WINDOW_SHOWN);
if (NULL == pWnd)
{
std::cout << "SDL Error: " << SDL_GetError() << std::endl;
return -1;
}
// 3. 创建渲染 SDL_RENDERER_ACCELERATED GPU硬件加速渲染
SDL_Renderer* pRenderer = SDL_CreateRenderer(pWnd, -1, SDL_RENDERER_ACCELERATED);
if (NULL == pRenderer)
{
SDL_DestroyWindow(pWnd);
std::cout << "SDL Error: " << SDL_GetError() << std::endl;
return -1;
}
// 4. 加载bmp图片到surface
SDL_Surface* pSurface = SDL_LoadBMP("./Panda.bmp"); // 加载bmp图片
if (NULL == pSurface)
{
SDL_DestroyRenderer(pRenderer);
SDL_DestroyWindow(pWnd);
std::cout << "SDL Error: " << SDL_GetError() << std::endl;
return -1;
}
SDL_Rect rect = { 0, 0, pSurface->w - 50, pSurface->h + 50 };
// 5. 根据Surface创建纹理
SDL_Texture* pTexture = SDL_CreateTextureFromSurface(pRenderer, pSurface);
if (NULL == pTexture)
{
SDL_FreeSurface(pSurface);
SDL_DestroyRenderer(pRenderer);
SDL_DestroyWindow(pWnd);
std::cout << "SDL Error: " << SDL_GetError() << std::endl;
return -1;
}
// 6. 绘制三部曲
SDL_RenderClear(pRenderer); // 清空一下渲染器(防止有残留的数据)
SDL_RenderCopy(pRenderer, pTexture, &rect, &rect); // 将纹理数据拷贝到渲染器缓冲区中
SDL_RenderPresent(pRenderer); // 刷新渲染器显示
SDL_Delay(2000);
// 7. 释放资源,退出
// 释放表面
if (pSurface)
{
SDL_FreeSurface(pSurface);
}
// 释放纹理
if (pTexture)
{
SDL_DestroyTexture(pTexture);
}
// 释放渲染
if (pRenderer)
{
SDL_DestroyRenderer(pRenderer);
}
// 释放窗口
if (pWnd)
{
SDL_DestroyWindow(pWnd);
}
SDL_Quit();
return 0;
}