C++SFML编程,想用Text做个输入控件,但是无法显示,并且中文乱码代码页936。,这个怎么修改或者有什么其他的替代方法?
#include <SFML/Graphics.hpp>
#include <string>
class InputText {
public:
InputText(const std::string& fontFile, int x, int y, int charSize) {
if (!font.loadFromFile(fontFile)) {
throw std::runtime_error("Failed to load font");
}
text.setFont(font);
text.setCharacterSize(charSize);
text.setFillColor(sf::Color::Black);
text.setPosition(x, y);
cursor.setSize(sf::Vector2f(1, text.getCharacterSize())); // 设置光标大小
cursor.setFillColor(sf::Color::Black); // 设置光标颜色
cursor.setPosition(text.getPosition().x + text.getGlobalBounds().width, text.getPosition().y); // 设置光标位置
background.setSize(sf::Vector2f(text.getGlobalBounds().width + 10, text.getGlobalBounds().height)); // 设置背景大小
background.setFillColor(sf::Color::White); // 设置背景颜色
background.setPosition(text.getPosition().x - 5, text.getPosition().y); // 设置背景位置
}
void handleEvent(const sf::Event& event) {
if (event.type == sf::Event::TextEntered) {
if (event.text.unicode < 128 || event.text.unicode >= 0x4E00 && event.text.unicode <= 0x9FFF) {
userInput += static_cast<char>(event.text.unicode);
text.setString(userInput);
updateCursorPosition(); // 更新光标位置
}
}
}
void draw(sf::RenderWindow& window) {
window.draw(background); // 绘制背景
window.draw(text);
window.draw(cursor); // 绘制光标
}
private:
void updateCursorPosition() {
cursor.setPosition(text.getPosition().x + text.getGlobalBounds().width, text.getPosition().y);
}
sf::Font font;
sf::Text text;
sf::RectangleShape cursor; // 光标形状
sf::RectangleShape background; // 背景形状
std::string userInput;
};
int main()
{
// 创建一个窗口
sf::RenderWindow window(sf::VideoMode(800, 600), "Input Text Example");
// 创建输入文本控件实例
InputText inputText("your_chinese_font.ttf", 10, 10, 24); // 替换为你支持中文的字体文件路径
// 主循环
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed) {
window.close();
}
else {
inputText.handleEvent(event);
}
}
window.clear();
inputText.draw(window);
window.display();
}
return 0;
}