Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c++ - sf::Texture as class member doesn't work?

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

Class members:

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

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);

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

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

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 :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is called the white square problem.

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);

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

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

myimg_texture.loadFromImage(myimg_image);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...