c++ - SFML 像素操作 - 改变窗口中单个字符的大小
问题描述
有没有办法改变窗口中单个像素的大小,因为我宁愿处理 8x8 像素而不是 1x1 的单个控制台字符。
解决方案
如果您想放大(或缩小)窗口中的所有内容,最简单的方法是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;
}
编译后,这将导致两个旋转的六面“圆圈”,一个像素化(通过渲染纹理的分辨率)和一个锐利(由于简单的放大):
推荐阅读
- c# - 覆盖 DataColumn 的 clone()
- r - 应用 if 函数根据另一个变量的值来识别变量的值
- c# - 将控件拖到窗体上时出现 NullReferenceException
- bash - 在 Docker 容器中运行多个 ROS 进程
- c# - 替换文本后删除 HTML 电子邮件 css
- javascript - 仅返回 JSON 的特定元素
- azure - 我正在从 Logic App 调用 MS-Graph 并收到“未经授权”错误
- java - ExecutorCompletionService 和 FixedThreadPool 执行器之间的区别
- python - 如何设置特定范围,以便获取该范围的值并在 python 中运行
- python-3.x - 使用iter方法的无限循环