很遗憾,我没有图片,只有白屏。我目前正在学习c ++和sdl。
错误消息:
SDL_image Error: Couldn't open test.jpg
我正在Windows 10计算机上使用Visual Studio。
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;;
string ExePath() {
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\\/");
return string(buffer).substr(0, pos);
}
int main(int argc, char* args[]) {
cout << "my directory is " << ExePath() << "\n";
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
std::cout << "SDL load fail" << std::endl;
return -1;
}
SDL_Window* window = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_SHOWN);
if (window == NULL) {
std::cout << "Window load fail." << std::endl;
return -1;
}
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
std::cout << "Renderer load fail." << std::endl;
return -1;
}
SDL_Texture* background = IMG_LoadTexture(renderer, "test.jpg");
if (background == NULL) {
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
SDL_Delay(5000);
return -1;
}
SDL_Rect pos;
pos.x = 20;
pos.y = 30;
pos.w = 460;
pos.h = 300;
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, background, NULL, &pos);
SDL_RenderPresent(renderer);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
atexit(SDL_Quit);
return 0;
}
我已经尝试了绝对路径。图片也位于正确的文件夹中。较小的图片,jpeg,png。我不知道。
答案 0 :(得分:1)
SDL图像是一个单独的库。您应该在使用它之前对其进行初始化。像这样:
////...
int imgFlags = IMG_INIT_JPG; // or IMG_INIT_PNG;
// not sure about the imgFlags parameter, read the docs.
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
}
/// the rest is the same...
SDL_Texture* background = IMG_LoadTexture(renderer, "test.jpg");
if (background == NULL) {
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
SDL_Delay(5000);
return -1;
}
/// ...
一些参考https://discourse.libsdl.org/t/help-with-initializing-sdl-image/23601
编辑:对于“更近一步”:我认为您的延迟在错误的位置。
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, background, NULL, &pos);
SDL_RenderPresent(renderer);
SDL_Delay(5000); //////// For example try putting int here
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
atexit(SDL_Quit);
std::cout << "Bye!" << std::endl;
return 0;