【问题标题】:why isn't the sfml image displayed?为什么不显示 sfml 图像?
【发布时间】:2020-11-22 04:36:42
【问题描述】:

我试图在我的 sfml 应用程序中设置背景, 但出现错误 代码:

 Image hero_image;
hero_image.loadFromFile("image/main.png");
Texture hero_texture;
hero_texture.loadFromImage((hero_image));

Sprite hero_sprite;
hero_sprite.setTexture(hero_texture);
hero_sprite.setPosition(50,30); 
//main loop
window.draw(hero_sprite);

错误:

Failed to load image "image/main.png". Reason: Unable to open file
Failed to create texture, invalid size (0x0)

【问题讨论】:

  • 好像是你的可执行文件在错误的工作目录下执行,或者镜像文件损坏,或者你没有读取文件的权限。
  • MikeCAT, soo...如何解决目录问题?...
  • 使用您的文件浏览器找出图像的位置。然后阅读 IDE 上的文档,了解在调试应用程序时将哪个文件夹设置为工作目录。第二种方法是简单地在你的 c++ 代码中创建一个文件,然后使用你的文件资源管理器来放置它。确定正确的工作目录后,调整图像文件的路径。
  • 您在使用 Visual Studio 吗?如果是这样,请记住,当从 Visual Studio 运行可执行文件时,您的 .exe 所在的目录不是您的活动目录。

标签: c++ g++ sfml


【解决方案1】:

第一个错误Failed to load image "image/main.png". Reason: Unable to open file 是因为您可能输入了错误的文件路径。通过路径"image/main.png",您的图像应位于名为image 的文件夹中,而您的名称为main.png 的图片应位于此文件夹中: )。当然,您的文件夹image 应该在您的项目位置内,其中包含.cpp.h 文件。 第二个错误是因为当 Image hero_image; 没有正确加载Failed to load image "image/main.png". Reason: Unable to open file 错误而不是您的 Image hero_image; 为空时。

同样使用您加载到sf::Texture 中的sf::Image 实例也是没有用的。尝试这样做:

sf::Texture hero_texture;
hero_texture.loadFromFile("image/main.png");
sf::Sprite hero_sprite;
hero_sprite.setTexture(hero_texture);

【讨论】:

  • 只是一个更正:图像文件必须与可执行文件位于同一目录,而不是 .cpp/.h 文件
  • @Diego 你是对的,如果你从你的可执行文件运行你的游戏。但是,如果您是从调试器或 IDE 运行游戏,那么您的资源必须在我提到的位置
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 2012-07-26
  • 2012-10-26
  • 2015-05-04
相关资源
最近更新 更多