我正在尝试使用 SDL 渲染一个点,但我似乎无法获得要渲染的点。我在代码中没有收到任何错误,它正在编译,但是窗口上没有显示任何内容。
代码:
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
int main() {
const int windowHeight = 600;
const int windowWidth = 800;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
return 1;
cout << "Initialization failed" << endl;
}
SDL_Window *window = SDL_CreateWindow("Practice making sdl Window",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth,
windowHeight, SDL_WINDOW_SHOWN);
if (window == NULL) {
SDL_Quit();
return 2;
}
SDL_Renderer *s;
const int pointLocationx = windowWidth/2;
const int pointLocationy = windowHeight/2;
SDL_RenderDrawPoint(s, pointLocationx, pointLocationy);
bool quit = false;
SDL_Event event;
while (!quit) {
//drawing particles
//setting up objects
//repeated over and over again
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
}
上面是我的代码。感谢任何建议,并非常感谢您的帮助。
最佳答案
您遗漏了几件事。第一个也是最重要的是你的渲染器没有初始化,这是用 SDL_CreateRenderer 完成的。 . 现在我们准备好在窗口上绘制了。为此,您需要在渲染器上设置颜色(此颜色用于 RenderDrawPoint 和 RenderDrawLine 等函数)。
绘制您的观点后,我们会将颜色设置为之前的颜色。我选择了黑色作为背景,白色作为点的颜色,你可以选择任何你需要的,在渲染器中设置颜色的函数是SDL_SetRenderDrawColor。 .
现在我们可以抽奖了,但是在每次抽奖之前你必须clear你的屏幕,对渲染器进行所有绘制调用,然后 show你画了什么。
这是一个完整的示例,其中包含关于您所遗漏内容的注释部分,我还将您的 drawPoint 移到了您的主循环中,因为在一天结束时您可能希望它位于何处。
但是(很少使用)如果你想画一次就再也不改变屏幕上的内容,那么你可以把它带到墙外,调用一次 clear 和 present 就可以了。
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
int main() {
const int windowHeight = 600;
const int windowWidth = 800;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
return 1;
cout << "Initialization failed" << endl;
}
SDL_Window *window = SDL_CreateWindow("Practice making sdl Window",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth,
windowHeight, SDL_WINDOW_SHOWN);
if (window == NULL) {
SDL_Quit();
return 2;
}
// We create a renderer with hardware acceleration, we also present according with the vertical sync refresh.
SDL_Renderer *s = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) ;
const int pointLocationx = windowWidth/2;
const int pointLocationy = windowHeight/2;
bool quit = false;
SDL_Event event;
while (!quit) {
//drawing particles
//setting up objects
//repeated over and over again
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
// We clear what we draw before
SDL_RenderClear(s);
// Set our color for the draw functions
SDL_SetRenderDrawColor(s, 0xFF, 0xFF, 0xFF, 0xFF);
// Now we can draw our point
SDL_RenderDrawPoint(s, pointLocationx, pointLocationy);
// Set the color to what was before
SDL_SetRenderDrawColor(s, 0x00, 0x00, 0x00, 0xFF);
// .. you could do some other drawing here
// And now we present everything we draw after the clear.
SDL_RenderPresent(s);
}
SDL_DestroyWindow(window);
// We have to destroy the renderer, same as with the window.
SDL_DestroyRenderer(s);
SDL_Quit();
}
关于c++ - 如何在sdl2中渲染一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49539717/