我写了下面的代码,但它不打印图片。我只看到黑屏,什么也没有。纹理拒绝出现。
这些代码只是我所遇到问题的例证。基本上,我的目标是创建带有特定对象的精灵TextureRect
并将其发送到main,在其中我可以为此精灵设置纹理,然后绘制它。
如果可以的话请告诉我
ps。我试图将纹理设置为方法内部的精灵,但后来我得到没有纹理的白色矩形
#include <SFML/Graphics.hpp>
class Sprite_draw
{
public:
sf::Sprite print()
{
sf::Sprite sprite;
sprite.setTextureRect(sf::IntRect(10, 10, 10, 10));
return sprite;
}
};
int main()
{
sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window");
while (app.isOpen())
{
sf::Event event;
while (app.pollEvent(event))
{
if (event.type == sf::Event::Closed)
app.close();
}
Sprite_draw sprite1;
sf::Texture texture;
texture.loadFromFile("cb.bmp");
sprite1.print().setTexture(texture);
app.clear();
app.draw(sprite1.print());
app.display();
}
return EXIT_SUCCESS;
}
您的Sprite_draw::print
函数有两个问题:一个是它按值返回一个对象,即它是一个副本。另一个问题是它是局部变量的副本。因此,每次调用该函数时,都会为局部变量创建一个新对象sprite
,并返回该对象的新副本。
第一个问题意味着每次您做
sprite1.print().setTexture(texture);
您只能修改函数返回的(临时)副本。第二个问题意味着,无论调用该函数多少次,它始终会为局部变量创建一个全新的对象。
一种可能的解决方案是使局部变量成为类中的成员变量,并返回对其的引用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句