我试图加载图片(" carnero.png")但是当我使用IMG_LoadTexture()时,它返回null;
Game.h
#ifndef GAME_H_
#define GAME_H_
#include <SDL.h>
#include <SDL_image.h>
#include <windows.h>
class Game {
public:
Game();
~Game();
void run();
void initGraphics();
void gameLoop();
private:
SDL_Window* _window = nullptr;
SDL_Renderer* _renderer;
SDL_Surface* _surfaceBMP;
SDL_Texture* _textureScenario;
SDL_Texture* _textureCarnero;
SDL_Rect* _scenarioRect;
SDL_Rect* _carneroRect;
int _width;
int _height;
bool _running;
};
#endif /* SRC_GAME_H_ */
Game.cpp
#include "Game.h"
#include <iostream>
Game::Game(){
_running = true;
run();
}
Game::~Game(){
}
void Game::run(){
initGraphics();
gameLoop();
}
void Game::initGraphics(){
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_PNG);
_window = SDL_CreateWindow("Carneiro", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_SHOWN);
if(_window == nullptr) exit(1);
_renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
_surfaceBMP = SDL_LoadBMP("textures/scenario.bmp");
_textureScenario = SDL_CreateTextureFromSurface(_renderer, _surfaceBMP);
SDL_FreeSurface(_surfaceBMP);
_textureCarnero = IMG_LoadTexture(_renderer, "/textures/carnero2.png");
if(_textureCarnero == nullptr) exit(1);
_scenarioRect->x = 0; _scenarioRect->w = 1024;
_scenarioRect->y = 0; _scenarioRect->h = 740;
_carneroRect->x = 20; _carneroRect->w = 150;
_carneroRect->y = 100; _carneroRect->h = 100;
}
void Game::gameLoop(){
while(_running){
Sleep(10);
SDL_Event evnt;
if(SDL_PollEvent(&evnt)){
switch(evnt.type){
case SDL_QUIT:
_running = false;
break;
}
}
SDL_RenderClear(_renderer);
SDL_RenderCopy(_renderer, _textureScenario, nullptr, _scenarioRect);
// SDL_QueryTexture(_textureCarnero, NULL, NULL, &_carneroRect->x, &_carneroRect->y);
SDL_RenderCopy(_renderer, _textureCarnero, nullptr, _carneroRect);
SDL_RenderPresent(_renderer);
}
SDL_DestroyTexture(_textureScenario);
SDL_DestroyTexture(_textureCarnero);
SDL_DestroyRenderer(_renderer);
SDL_DestroyWindow(_window);
SDL_Quit();
IMG_Quit();
}
此函数返回null
_textureCarnero = IMG_LoadTexture(_renderer, "/textures/carnero2.png");
但是当我使用SDL_LoadBMP()加载背景时,它可以工作。我尝试将我的.png放在其他文件夹中,但它也无法正常工作。我也尝试使用IMG_LOAD()加载我的.png,但我没有成功。
答案 0 :(得分:1)
您的路径不正确。 /textures/carnero2.png
会在C:\textures\carnero2.png
上搜索文件,或在unix上搜索/textures/carnero2.png
。
您可以按如下方式解决此问题:
C:\Program Files (x86)\MyGame\textures\carnero2.png
,/usr/local/share/mygame/textures/carnero2.png
./textures/carnero2.png
textures/carnero2.png
。答案 1 :(得分:0)
输入文件的路径可能不正确:
/textures/carnero2.png
应该是
textures/carnero2.png
与上一个(工作)加载命令类似。
将来,我建议您在尝试加载文件之前测试文件是否存在。所以你可以分开&#34;找不到文件&#34;来自真实格式/损坏文件问题的错误。