首页 > 解决方案 > SFML 像素操作 - 改变窗口中单个字符的大小

问题描述

有没有办法改变窗口中单个像素的大小,因为我宁愿处理 8x8 像素而不是 1x1 的单个控制台字符。

标签: c++sfml

解决方案


如果您想放大(或缩小)窗口中的所有内容,最简单的方法是sf::View通过调用更改窗口sf::RenderWindow::setView()

sf::RenderWindow myWindow(sf::VideoMode(640, 480), "Test");

// Define a view that's 320x240 units (i.e. pixels) in size and is centered at (160, 120)
sf::View myView(sf::Vector2f(160, 120), sf::Vector2f(320, 240));

// Apply the view
myWindow.setView(myView);

运行此代码后,渲染到窗口的所有内容都将放大 2 倍(因为您在 640x480 中显示 320x240)。以类似的方式,您可以实现 8 的缩放因子,例如通过将窗口设置为 (800, 800) 并将视图设置为 (100, 100)。

但是,根据您渲染的内容,您不会得到像素化的外观。

如果您想创建具有锐利/放大像素的像素艺术,我建议您将场景渲染为所需分辨率的渲染纹理,然后将该纹理渲染到实际窗口,放大(并禁用过滤):

#include <SFML/Graphics.hpp>

int main(int argc, char **argv) {
    sf::RenderWindow window(sf::VideoMode(800, 600), "Scaling", sf::Style::Default);

    // Set the view to upscale
    // Use 1/8th of the window's size
    sf::View view(sf::Vector2f(50, 37.5f), sf::Vector2f(100, 75));
    window.setView(view);

    // Let's create a render texture as buffer
    // (I'm skipping error checking for simplicity)
    sf::RenderTexture buffer;
    buffer.create(100, 75); // Again 1/8th of the window size

    sf::Sprite bufferSprite(buffer.getTexture());

    // Something to draw
    sf::CircleShape circle(20, 6);
    circle.setFillColor(sf::Color::Transparent);
    circle.setOutlineColor(sf::Color::Black);
    circle.setOutlineThickness(2);
    circle.setOrigin(20, 20); // Move origin to center

    // Let's use a simple sf::Clock to animate a bit
    sf::Clock timer;

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            switch (event.type) {
            case sf::Event::Closed:
                window.close();
                break;
            }
        }

        // Rotate the circle
        circle.setRotation(timer.getElapsedTime().asMilliseconds() / 10);

        // Clear the scene in the render texture
        buffer.clear(sf::Color(64, 127, 192));

        // Draw our circle
        circle.setPosition(25, 37.5f); // Despite the float offset, the result will be pixel accurate!
        buffer.draw(circle);

        // Finish the render texture drawing
        buffer.display();

        // Draw the render texture's contents
        window.draw(bufferSprite);

        // Let's render the upscaled shape for comparison
        circle.setPosition(75, 37.5f);
        window.draw(circle);

        // Display the results
        window.display();
    }

    return 0;
}

编译后,这将导致两个旋转的六面“圆圈”,一个像素化(通过渲染纹理的分辨率)和一个锐利(由于简单的放大):

示例程序正在运行。


推荐阅读