我正在尝试使用 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();
}
Run Code Online (Sandbox Code Playgroud)
上面是我的代码。任何建议都将受到赞赏,并且非常感谢帮助。
你错过了几件事。第一个也是最重要的是您的渲染器未初始化,这是通过SDL_CreateRenderer完成的。现在我们准备在窗口上绘图了。为此,您需要在渲染器上设置一种颜色(此颜色用于 RenderDrawPoint 和 RenderDrawLine 等函数)。
画出你的观点后,我们将把颜色设置为之前的颜色。我选择黑色作为背景,白色作为点的颜色,你可以选择任何你需要的,渲染器中设置颜色的函数是SDL_SetRenderDrawColor。
现在我们可以绘制了,但是在每次绘制之前,您必须清除屏幕,对渲染器进行所有绘制调用,然后显示您绘制的内容。
这是一个完整的示例,其中包含您所缺少的注释部分,我还将您的drawPoint移到了主循环中,因为最终这就是您可能想要的位置。
但是(非常罕见的使用)如果您想绘制一次并且不再更改屏幕上的内容,那么您可以将其带到墙外,调用clear并呈现一次并完成它。
#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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5225 次 |
| 最近记录: |