I'm currently working in SFML for c++ and trying to resize a window however the solution I found to my problem doesn't quite feel right and I'm looking if there is a better way.
I have an object that gets resized multiple times so it may fit inside the window or not, I have to expand the window if its bigger and shrink it if its smaller. However I have a minimum size for the window, if the object fits inside that I want to reset the window to that size.
This is the pseudo-code I'm using right now:
if (Object.getSize().x > window.getSize().x || Object.getSize().y > window.getSize.y){
if(Object.getSize().x > windowMinSize.x){
window.resize(Object.getSize().x, window.getSize().y)
}
if(Object.getSize().y > windowMinSize.y){
window.resize(window.getSize().x, Object.getSize().y)
}
}
else{
window.resize(windowMinSize);
}
I've looked into switch
and other options but I haven't found what I'm looking for.
I'm a bit confused, because in the end it sounds like you want to simply resize your window to the object size while keeping a specific minimum size.
As such all you'd need is a simple call to std::max()
to determine the bigger value of two inputs:
unsigned int width = std::max(min_width, object_width);
unsigned int height = std::max(min_height, object_height);
When using the new size it will basically resize the window to match your object unless the object is smaller than your minimum size.
You can use the same pattern to also add a maximum size using std::min()
as an additional layer:
unsigned int width = std::min(max_width, std::max(min_width, object_width));
unsigned int height = std::min(max_height, std::max(min_height, object_height));
Edit: As bolov correctly suggested, this can be simplified even more for modern compilers using the new std::clamp
:
unsigned int width = std::clamp(object_width, min_width, max_width);
unsigned int height = std::clamp(object_height, min_height, max_height);