我正在尝试使用sdl2在窗口中绘制网格。程序运行时,即使被调用SDL_RenderPresent()
,有时也无效,导致透明窗口空白。其他时候,程序正在提供正确的输出。
#include "SDL.h"
#include <stdio.h>
#include <stdlib.h>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
const SDL_Color BLACK = { .r = 0, .g = 0, .b = 0, .a = 255 };
const SDL_Color WHITE = { .r = 255, .g = 255, .b = 255, .a = 255 };
const SDL_Color GRAY = { .r = 128, .g = 128, .b = 128, .a = 255 };
const SDL_Color RED = { .r = 255, .g = 0, .b = 0, .a = 255 };
const SDL_Color MAROON = { .r = 128, .g = 0, .b = 0, .a = 255 };
const SDL_Color BLUE = { .r = 0, .g = 0, .b = 255, .a = 255 };
const SDL_Color NAVY = { .r = 0, .g = 0, .b = 128, .a = 255 };
const SDL_Color LIME = { .r = 0, .g = 255, .b = 0, .a = 255 };
const SDL_Color GREEN = { .r = 0, .g = 128, .b = 0, .a = 255 };
const int P_SIZE = 10;
void draw_grid(SDL_Renderer *renderer)
{
SDL_Color prev;
SDL_GetRenderDrawColor(renderer, &prev.a, &prev.g, &prev.b, &prev.a);
SDL_SetRenderDrawColor(renderer, GRAY.r, GRAY.g, GRAY.b, GRAY.a);
// drawing the axes
SDL_RenderDrawLine(renderer, SCREEN_WIDTH / 2, 0,
SCREEN_WIDTH / 2, SCREEN_HEIGHT); // the Y-axis
SDL_RenderDrawLine(renderer, 0, SCREEN_HEIGHT / 2,
SCREEN_WIDTH, SCREEN_HEIGHT / 2); // the X-axis
SDL_SetRenderDrawColor(renderer, BLACK.r, BLACK.g, BLACK.b, BLACK.a);
// drawing the grid
for (int i = 0; i <= SCREEN_WIDTH; i += P_SIZE) {
if (i == SCREEN_WIDTH / 2) {
continue;
}
SDL_RenderDrawLine(renderer, i, 0, i, SCREEN_HEIGHT);
}
for (int i = 0; i <= SCREEN_HEIGHT; i += P_SIZE) {
if (i == SCREEN_HEIGHT / 2) {
continue;
}
SDL_RenderDrawLine(renderer, 0, i, SCREEN_WIDTH, i);
}
SDL_SetRenderDrawColor(renderer, prev.a, prev.g, prev.b, prev.a);
}
int main()
{
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "\nUnable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Quit);
SDL_Window *window =
SDL_CreateWindow("Clipping",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN
);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == NULL) {
fprintf(stderr, "\nRenderer could not be created:%s\n", SDL_GetError());
return 1;
}
SDL_SetRenderDrawColor(renderer, WHITE.r, WHITE.g, WHITE.b, WHITE.a);
SDL_RenderClear(renderer);
draw_grid(renderer);
SDL_RenderPresent(renderer);
int quit = 0;
while (!quit) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
quit = 1;
break;
default:
break;
}
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
return 0;
}