使用SDL2显示灰阶格式图片的示例代码
时间: 2023-03-05 09:53:36 浏览: 149
以下是一个使用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函数来处理退出事件,等待用户关闭窗口。
阅读全文