我正在调用SDL_RenderCopy,它会被调用并正常返回,但不会在窗口上绘制任何内容。编辑以使问题和代码更清晰。我想我可能正在尝试使用超出其范围的某些内容,因此无法调用它,但这不会产生任何错误,因此我不确定。这是我指的https://commons.wikimedia.org/wiki/Category:PNG_chess_pieces/Standard_transparent#/media/File:Chess_kdt60.png
的简单图片#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
// Recreation of the problem. Doesnt draw anything onto the white screen.
class King{
public:
King(SDL_Renderer *renderer){
SDL_Surface *Piece;
Piece = IMG_Load("Pieces/BK.png"); // I'll attach the picture
king = SDL_CreateTextureFromSurface(renderer, Piece);
SDL_FreeSurface(Piece);
kingRect.h = 100;
kingRect.w = 100;
}
~King(){}
void render(SDL_Renderer *renderer){
SDL_RenderCopy(renderer, king, NULL, &kingRect); // 99% sure the problem is this
}
private:
SDL_Texture *king;
SDL_Rect kingRect;
};
class Game {
public:
Game(const char *title, int sidelength){
isRunning = true;
if(SDL_Init(SDL_INIT_EVERYTHING) != 0) isRunning = false;
window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sidelength, sidelength, SDL_WINDOW_OPENGL);
if(window == NULL) isRunning = false;
renderer = SDL_CreateRenderer(window, -1, 0);
if(!renderer) isRunning = false;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
~Game(){}
void handleEvents(){
//Handles Events. I know this works.
}
}
void update(){};
void render(){
SDL_RenderClear(renderer);
BK.render(renderer);
SDL_RenderPresent(renderer);
}
void clean(){
//Cleans up after. I know this works.
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
}
bool running(){return(isRunning);}
King BK{renderer};
private:
bool isRunning{true};
SDL_Window *window;
SDL_Renderer *renderer;
};
Game *game = nullptr;
int main(int argc, const char *argv[]){
game = new Game("Testing Window", 800);
while(game->running()){
game->handleEvents();
game->update();
game->render();
}
game->clean();
return(0);
}
答案 0 :(得分:1)
King BK{renderer};
字段会在您的Game::Game
完成之前初始化,并有机会分配渲染器,因此它将获得NULL
。 NULL
不是有效的渲染器,无法创建纹理。如果您将检查错误,则将收到Invalid renderer
消息。同样,启用警告的体面编译器也会发出类似warning: 'Game::renderer' is used uninitialized in this function [-Wuninitialized]
的信息;考虑在编译器中启用更好的警告级别。
第二件事是,您从未以要加载的必需图像格式调用IMG_Init
。
第三件事是代码格式错误,未经修改就无法编译。我建议测试您发布为MCCVE的代码,使其仍然可以编译并重现您的问题(正如MCCVE所暗示的那样)。