#include
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "Button Test");
// 按钮图形元素
sf::RectangleShape button(sf::Vector2f(100, 50));
button.setFillColor(sf::Color::Green);
button.setPosition(50, 50);
// 鼠标位置
sf::Vector2i mousePos;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
// 处理鼠标点击事件
if (event.type == sf::Event::MouseButtonPressed)
{
// 获取当前鼠标位置
mousePos = sf::Mouse::getPosition(window);
// 判断鼠标是否在按钮内
if (button.getGlobalBounds().contains(sf::Vector2f(mousePos.x, mousePos.y)))
{
// 按钮被点击了
button.setFillColor(sf::Color::Red);
}
}
// 处理鼠标释放事件
if (event.type == sf::Event::MouseButtonReleased)
{
// 恢复按钮颜色
button.setFillColor(sf::Color::Green);
}
}
window.clear();
window.draw(button);
window.display();
}
return 0;
}
在主循环中,我们不断监听鼠标事件。
当鼠标被按下时,我们需要获取鼠标的位置并判断是否在按钮内。如果是,我们改变按钮的颜色,表示按钮被按下了。
当鼠标被释放时,我们将按钮的颜色恢复成原来的颜色,表示按钮被松开了。
完整代码如下: