SDL2显示问题

初次结束SDL,版本为2.0.8,使用环境为MaxOS。

参考网上的例子写了一个player程序,编译没有问题,运行过程中没有任何报错。

但是SDL2创建的窗口显示不出来,真让人苦恼。

综合种种现象和以往经历,这肯定是一个小问题,很可能是惯用用法不正常或者有遗漏造成的。

最终经过大量的实验调整,添加如下代码,窗口得以重见天日:

SDL_Event event;
if (SDL_PollEvent(&event)) {
     printf("event is %#x\n", event.type); // test code
     if (SDL_QUIT == event.type) {
          cout << "SDL2 quit" << endl;
          break;
     }
}

居然是事件!!!

特写此博客,铭记这血的教训,希望也能为他人带来些许帮助。

------------------------------------------------------------------------------------

通过test code,结合type的各个值,大胆推测一下:

依靠SDL_PollEvent()从事件队列中提取事件。

SDL2依靠事件驱动,包含设备状态,鼠标状态,窗口状态等一系列事件,事件被提取作为事件处理标准。

但是事件不能堆积在事件队列中,哪怕是被丢掉。

多次实验,发现每次程序启动后,最新过来的事件号是0x1100。

SDL_AUDIODEVICEADDED = 0x1100, /**< A new audio device is available */

那么该事件号很可能为窗口准备完成的标志,如果不poll出来的话,窗口将一直处于等待状态。

大概就是这个样子吧,希望看到的大神指正一下。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个使用SDL2显示灰阶格式图片的示例代码,其中假设灰阶图片的宽度为width,高度为height,像素值存储在名为pixels的unsigned char类型数组中: ``` #include <SDL2/SDL.h> int main(int argc, char* argv[]) { SDL_Window* window = NULL; SDL_Surface* surface = NULL; SDL_Event event; unsigned char* pixels = NULL; int width = 640; int height = 480; if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); return 1; } window = SDL_CreateWindow("Gray Image", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); return 1; } surface = SDL_GetWindowSurface(window); if (surface == NULL) { printf("Surface could not be created! SDL_Error: %s\n", SDL_GetError()); return 1; } pixels = (unsigned char*)surface->pixels; // 将像素值拷贝到surface中 for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int index = i * width + j; pixels[index] = pixels[index + 1] = pixels[index + 2] = pixels[index + 3] = pixels[index]; } } // 更新surface SDL_UpdateWindowSurface(window); while (1) { if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { break; } } } SDL_DestroyWindow(window); SDL_Quit(); return 0; } ``` 代码中,先创建一个窗口,然后获取该窗口的表面(surface)并将其存储在指针surface中。接下来,将unsigned char类型数组中的像素值拷贝到surface->pixels中,并将其显示窗口上。最后,使用SDL_PollEvent函数来处理退出事件,等待用户关闭窗口
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值