这是我的代码,没有错误或警告。我不明白我在哪里错。
它应该显示一个带有矩形的窗口。
#include <stdio.h>
#include <SDL.h>
int main(int argc, const char * argv[]) {
SDL_Window *window; // Declare a window
SDL_Renderer *renderer; // Declare a renderer
SDL_Init(SDL_INIT_VIDEO); //Initialize SDL2
//Create an application window with the fellowing settings:
window = SDL_CreateWindow("Game Window", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
640, // width, in pixels
480, // height, in pixels
0 ); // flag);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
//
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
//Clear the screen (to blue)
SDL_RenderClear(renderer);
// set the drawing color to white
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_Rect rect = {220, 140, 200, 200};
SDL_RenderFillRect(renderer, &rect);
// We are done drawing, "present" or show to the screen what we have drawn
SDL_RenderPresent(renderer);
// Wait a few seconds before quitting
SDL_Delay(2000);
// Close and destroy the window
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
// Clean up
SDL_Quit();
return 0;
}
绘制和延迟是不可靠的方法。它可在某些OS /窗口管理器上工作,以实现短暂的延迟,但不适用于其他系统。您需要处理事件(否则可能会收到“应用程序挂起”提示)并在窗口管理器要求您重绘时重绘-或只是无条件重绘。
#include <stdio.h>
#include <SDL.h>
int main(int argc, char * argv[]) {
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("SDL_Init error: %s\n", SDL_GetError());
return 1;
}
SDL_Window *window = SDL_CreateWindow("Game Window",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
640, 480, 0);
if(!window) {
printf("SDL_CreateWindow error: %s\n", SDL_GetError());
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if(!renderer) {
printf("SDL_CreateRenderer error: %s\n", SDL_GetError());
return 1;
}
// get timestamp when main loop have started
Uint32 start_time = SDL_GetTicks();
int quit = 0;
while(!quit) {
/* process events - essential part. Even if you don't want to react to events,
* SDL_PollEvent (or SDL_PumpEvents) needs to be called frequently */
SDL_Event ev;
while(SDL_PollEvent(&ev)) {
if(ev.type == SDL_QUIT) {
// e.g. window closed
quit = 1;
break;
}
}
// draw your frame
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_Rect rect = {220, 140, 200, 200};
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);
if(SDL_GetTicks() - start_time > 2000) {
// running longer than 2 seconds, break main loop
quit = 1;
}
}
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
return 0;
}