What I'm trying to do as the moment is trying to resize my chessboard sprite so that it fits the entire screen when the user tries to resize the window but the problem that I'm having is that the sprite looks all stretched out and ugly.
So what I tried to do was to check for a resizing event and then I divide the new screen size with the old screen size and multiply it by 100 to get the scale factor in the x and y axis but this didn't help at all.
The video mode is set to 700, 703, 24 because that is the exact width, height and bit depth that the png image has so that is why I made that resolution the default one.
Main.cpp
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Event.hpp>
#include "Board.hpp"
void checkInput(sf::RenderWindow &, Board chessBoard);
void resizeObjects(sf::RenderWindow &, Board chessBoard, sf::Event);
void updateScreen(sf::RenderWindow &, sf::Sprite);
int main()
{
sf::RenderWindow gameWindow(sf::VideoMode(700, 703, 24), "Chess");
sf::Texture textureBoardPath;
textureBoardPath.loadFromFile("ChessBoard.png");
Board chessBoard(textureBoardPath);
while (gameWindow.isOpen())
{
checkInput(gameWindow, chessBoard);
updateScreen(gameWindow, chessBoard.getBoard());
}
return 0;
}
void checkInput(sf::RenderWindow &gameWindow, Board chessBoard)
{
sf::Event event;
while (gameWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
gameWindow.close();
}
else if (event.type == sf::Event::Resized)
{
resizeObjects(gameWindow, chessBoard, event);
}
}
}
void resizeObjects(sf::RenderWindow &gameWindow, Board chessBoard, sf::Event event)
{
float scaleXFactor = event.size.width / gameWindow.getView().getSize().x * 100;
float scaleYFactor = event.size.height / gameWindow.getView().getSize().y * 100;
chessBoard.resizeBoard(scaleXFactor, scaleYFactor);
}
void updateScreen(sf::RenderWindow &gameWindow, sf::Sprite chessBoard)
{
gameWindow.clear();
gameWindow.draw(chessBoard);
gameWindow.display();
}
Board.hpp
#pragma once
#include <SFML/Graphics/Sprite.hpp>
class Board
{
public:
Board(const sf::Texture &);
sf::Sprite getBoard() const;
void resizeBoard(float, float);
private:
int board[8][8] =
{ -1,-2,-3,-4,-5,-3,-2,-1
-6,-6,-6,-6,-6,-6,-6,-6,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
6, 6, 6, 6, 6, 6, 6, 6,
1, 2, 3, 4, 5, 3, 2, 1 };
sf::Sprite spriteBoard;
sf::Sprite chessPieces[32];
};
Board.cpp
#include "Board.hpp"
#include <SFML/Graphics/Texture.hpp>
Board::Board(const sf::Texture &textureBoardPath): spriteBoard(textureBoardPath)
{
}
sf::Sprite Board::getBoard() const
{
return spriteBoard;
}
void Board::resizeBoard(float scaleXFactor, float scaleYFactor)
{
spriteBoard.setScale(scaleXFactor, scaleYFactor);
}