重复纹理以适应 SFML 中的特定尺寸 [英] Repeating texture to fit certain size in SFML
问题描述
我有一个包含纹理的文件.我将它加载到 sf::Texture
并用 setTextureRect
拆分成精灵.
I have a file that contains textures. I load it to sf::Texture
and split into sprites with setTextureRect
.
现在假设一个精灵包含 20 像素宽的纹理部分.如何渲染它以适应例如宽度213 像素.我能想到的唯一方法是将它渲染到 sf::RenderTexture
并用另一个精灵裁剪它.
Now lets say one sprite contains part of texture that is 20 pixels wide. How can I render it to fit width of e.g. 213 pixels. The only way I can think about is to render it to sf::RenderTexture
and crop it with another sprite.
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
您可以使用 sf::Texture::setRepeated
做到这一点.
You can use sf::Texture::setRepeated
to do that.
但是,您需要将较大图像的那部分复制到独立的纹理中.
However, you'll need to copy that part of your bigger image into an independant texture.
这是一个例子:
#include <SFML/Graphics.hpp>
int main(int, char const**)
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
sf::Image img;
img.create(20, 20);
for (auto i = 0; i < 20; ++i) {
for (auto j = 0; j < 20; ++j) {
img.setPixel(i, j, sf::Color(255 * i / 20, 255 * j / 20, 255 * i / 20 * j / 20));
}
}
sf::Texture texture;
texture.loadFromImage(img);
texture.setRepeated(true);
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect({ 0, 0, 800, 600 });
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
window.clear();
window.draw(sprite);
window.display();
}
return EXIT_SUCCESS;
}
这篇关于重复纹理以适应 SFML 中的特定尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!