SDL_Renderer有点问题。我不明白为什么它不起作用。让我们看一下这个例子,它运行正常:
bool running = true;
SDL_Window* window = SDL_CreateWindow("ASDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Texture* texture = IMG_LoadTexture(renderer, "asdf.bmp");
SDL_Event event;
while(running)
{
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
if(event.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
break;
default:
break;
}
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
然后它来到了类,当我通过函数传递渲染器时,它不再工作了。
class Sprite
{
public:
Sprite(const std::string& path) : filePath(path) {};
~Sprite() { SDL_DestroyTexture(tex); };
void draw(SDL_Renderer* renderer);
private:
const std::string& filePath;
SDL_Texture* tex;
};
void Sprite::draw(SDL_Renderer* renderer)
{
printf("renderer sprite = %p\n", renderer);
tex = IMG_LoadTexture(renderer, filePath.c_str());
SDL_RenderCopy(renderer, tex, NULL, NULL);
}
int main(int argc, char **argv)
{
bool running = true;
SDL_Window* window = SDL_CreateWindow("ASDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Event event;
Sprite* sprite = new Sprite("asdf.bmp");
while(running)
{
printf("renderer main = %p\n", renderer);
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
if(event.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
break;
default:
break;
}
}
SDL_RenderClear(renderer);
sprite->draw(renderer);
SDL_RenderPresent(renderer);
}
return 0;
}
渲染器的地址在main和draw函数中是相同的。我知道我可能在这里犯了一些初学者的错误,但我无法找到它。
答案 0 :(得分:1)
当您致电sprite->draw
时,每帧都会加载纹理。
您应该将行tex = IMG_LoadTexture(renderer, filePath.c_str());
移动到构造函数中,以便只加载一次。
原因是纹理不能在与加载它的帧相同的情况下进行渲染。
作为旁注,您似乎没有使用各自的销毁功能清除SDL_Window
或SDL_Renderer
或调用SDL_Quit
,但我接受这可能已被省略提交代码示例。