SDL_RenderCopy 什么都不做

SDL_RenderCopy not doing anything

我正在调用 SDL_RenderCopy,它被调用并且 returns 正常,但没有向 window 绘制任何内容。编辑以使问题和代码更清晰。我在想我可能会尝试使用超出其范围的东西,因此无法调用它,但这不会产生任何错误,所以我不确定。这是我参考的简单图片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);
}

King BK{renderer}; 字段在您的 Game::Game 完成并有机会分配渲染器之前被初始化,因此它得到 NULLNULL 不是有效的渲染器,无法创建纹理。如果您检查错误,您会收到 Invalid renderer 消息。启用警告的体面编译器也会告诉类似 warning: 'Game::renderer' is used uninitialized in this function [-Wuninitialized];考虑在编译器中启用更好的警告级别。

第二件事是,您从未调用 IMG_Init 想要加载的所需图像格式。

第三件事是代码格式错误,如果不修改就无法编译。我建议测试您 post 作为 MCCVE 的代码,以便仍然可以编译并重现您的问题(正如 MCCVE 暗示的那样)。