Skip to content

Instantly share code, notes, and snippets.

@adventurist
Created January 16, 2022 20:19
Show Gist options
  • Save adventurist/b1fa5fe5a91f3c67e3cf383120a72a86 to your computer and use it in GitHub Desktop.
Save adventurist/b1fa5fe5a91f3c67e3cf383120a72a86 to your computer and use it in GitHub Desktop.
dimensions
struct Dimensions
{
static constexpr int square = 1;
static constexpr float landscape = 1.91f;
static constexpr float vertical = 0.8f;
Dimensions(int width_, int height_)
:
ratio(ComputeRatio(width_, height_)),
width(width_),
height(height_),
type(DetectDimensions(width_, height_, ratio))
{}
float ratio;
int width;
int height;
DimensionType type;
bool is_square() const { return (type == DimensionType::square); }
bool is_landscape() const { return (type == DimensionType::landscape); }
bool is_vertical() const { return (type == DimensionType::vertical); }
QRect Get()
{
if (is_square())
{
if (height != width)
return (height > width) ? QRect{ 0, (height - width) / 2, width, width} :
QRect{(width - height) / 2, 0, height, height};
else
return QRect{0, 0, height, width};
}
const float target = (is_landscape()) ? landscape : vertical;
if (ratio < target)
height = (width * (1 / target));
else
width = (height * target);
return QRect{(height / 2), (width / 2), height, width}; // First two values are WRONG
}
static DimensionType DetectDimensions(const int width, const int height, const float& ratio)
{
if (width == height)
return DimensionType::square;
auto sq_delta = std::fabs(square - ratio);
auto ls_delta = std::fabs(landscape - ratio);
auto vt_delta = std::fabs(vertical - ratio);
return (sq_delta < ls_delta) ?
(sq_delta < vt_delta) ? DimensionType::square :
DimensionType::vertical :
(ls_delta < vt_delta) ? DimensionType::landscape :
DimensionType::vertical;
}
static float ComputeRatio(int width, int height) { return static_cast<float>(width) / static_cast<float>(height); }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment