SFML 将 txt 文件中的图像加载到矢量中只加载最后一张图像
SFML Loading images from txt file into vector only loads last image
我正在尝试将 6 张图像加载到 std::vector(sf::Sprite)
到我的状态机中。状态机工作正常,所以我怀疑这是问题所在。
我有一个包含图像文件名的 .txt 文件
1.png
2.png
3.png
4.png
5.png
6.png
图像本身位于 img/
目录中。
相关代码如下:
std::ifstream file("images.txt");
while (!(file.eof()))
{
getline(file, TmpString);
filename.push_back(TmpString);
}
TmpString
只是一个字符串变量,用于存储单个图像的文件名。 filename
是一个字符串向量,使用断点,我可以看到它有正确的字符串(也就是正确的文件名)。
在下一个循环中,我使用 loadFromFile()
将图像加载到名为 tempTex
的 sf::Texture
中。我设置了一个名为 tempSprite
的 sf::Sprite
的纹理,并将其添加到 spriteList
,即 std::vector<sf::Sprite>
。
for (size_t i = 0; i < filename.size(); i++)
{
tempTex.loadFromFile("img/" + filename[i]);
tempSprite.setTexture(tempTex, true);
spriteList.push_back(tempSprite);
}
问题是,每当我从 spriteList 中绘制任何精灵到 window 时,它总是 6.png
图像。即:
m_window.draw(spriteList[index])
总是绘制 6.png
无论索引是什么。
When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer.
根据我的理解,这也意味着如果您将新纹理加载到同一个对象中,它将被覆盖。精灵仍将指向现在已更改的相同纹理。您需要保留一组纹理。
我正在尝试将 6 张图像加载到 std::vector(sf::Sprite)
到我的状态机中。状态机工作正常,所以我怀疑这是问题所在。
我有一个包含图像文件名的 .txt 文件
1.png
2.png
3.png
4.png
5.png
6.png
图像本身位于 img/
目录中。
相关代码如下:
std::ifstream file("images.txt");
while (!(file.eof()))
{
getline(file, TmpString);
filename.push_back(TmpString);
}
TmpString
只是一个字符串变量,用于存储单个图像的文件名。 filename
是一个字符串向量,使用断点,我可以看到它有正确的字符串(也就是正确的文件名)。
在下一个循环中,我使用 loadFromFile()
将图像加载到名为 tempTex
的 sf::Texture
中。我设置了一个名为 tempSprite
的 sf::Sprite
的纹理,并将其添加到 spriteList
,即 std::vector<sf::Sprite>
。
for (size_t i = 0; i < filename.size(); i++)
{
tempTex.loadFromFile("img/" + filename[i]);
tempSprite.setTexture(tempTex, true);
spriteList.push_back(tempSprite);
}
问题是,每当我从 spriteList 中绘制任何精灵到 window 时,它总是 6.png
图像。即:
m_window.draw(spriteList[index])
总是绘制 6.png
无论索引是什么。
When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer.
根据我的理解,这也意味着如果您将新纹理加载到同一个对象中,它将被覆盖。精灵仍将指向现在已更改的相同纹理。您需要保留一组纹理。