sf :: Texture作为类成员不工作? [英] sf::Texture as class member doesn't work?

查看:216
本文介绍了sf :: Texture作为类成员不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Heyy,我想在我的SFML应用程序中绘制一个sprite,但是当我使用作为类成员的图像和纹理时,它的纹理总是为白色

Heyy, I want to draw a sprite in my SFML application but its texture is always white when I use an image and a texture that are class members

sf::Sprite myimg;
sf::Image myimg_image;
sf::Texture myimg_texture;

当我在我的cpp文件中创建这样的sprite

When I then create the sprite like this in my cpp file

// create image
myimg_image.create(icon.width, icon.height, icon.pixelData);

// create texture from image
myimg_texture.create(icon.width, icon.height);
myimg_texture.update(myimg_image);

// apply texture to sprite
myimg.setTexture(myimg_texture);

当我使用window.draw(myimg)绘制时,它只绘制一个白色sprite

It only draws a white sprite when I draw it with window.draw(myimg)

(图标是一个包含图像信息的结构。它只是我想使用导出为C源代码与GIMP的图像)

(icon is a struct that contains the image information.. it's just the image I want to use exported as C source with GIMP)

我试验了一点,意识到当我创建上面提到的类成员不作为类成员,而是作为局部变量在main函数中,图像绘制正确...

I experimented a bit and realised that when I create the above mentioned class members not as class members but as local variables within the main function, the image is drawn properly...

但是这不能帮助我,因为我需要他们作为成员,因为我想从其他功能访问他们

But that doesn't help me as I need them as members because I want to access them from other functions as well

你能帮我不知道该怎么做:(

Can you please help me I just don't know what to do anymore :(

推荐答案

这叫做白色方块问题

基本上,在某些时候,您的对象被复制,但是复制构造函数不会更新复制的精灵纹理以使用复制的纹理,并且原始纹理被破坏,因此复制的精灵不再具有有效的纹理。

Basically, at some point, your object is copied but the copy constructor doesn't update the copied sprite texture to use the copied texture, and the original texture is destroyed so the copied sprite doesn't have a valid texture anymore.

快速修复可以简单地在复制构造函数和复制赋值运算符中运行初始化代码。

A quick fix can simply run the initialisation code inside the copy constructor and copy assignment operator.

BTW

myimg_texture.create(icon.width, icon.height);
myimg_texture.update(myimg_image);

可以直接使用 icon.pixelData myimg_image ,因此你根本不需要 sf :: Image

can directly use icon.pixelData instead of myimg_image and thus you don't need an sf::Image at all.

或者如果你需要 sf :: Image 用于另一个目的,你可以这样做:

Or you can do as follow if you need the sf::Image for another purpose:

myimg_texture.loadFromImage(myimg_image);

这篇关于sf :: Texture作为类成员不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆