Skip to content

Instantly share code, notes, and snippets.

@fosterbrereton
Last active August 29, 2015 13:55
Show Gist options
  • Save fosterbrereton/8738120 to your computer and use it in GitHub Desktop.
Save fosterbrereton/8738120 to your computer and use it in GitHub Desktop.
Rectangle Fitting
#include <iostream>
struct rect_t
{
float top_m;
float left_m;
float bottom_m;
float right_m;
float height() const { return bottom_m - top_m; }
float width() const { return right_m - left_m; }
};
rect_t operator*(const rect_t& src, float scale)
{
return rect_t{src.top_m * scale,
src.left_m * scale,
src.bottom_m * scale,
src.right_m * scale};
}
rect_t operator/(const rect_t& src, float scale)
{
return rect_t{src.top_m / scale,
src.left_m / scale,
src.bottom_m / scale,
src.right_m / scale};
}
std::ostream& operator<<(std::ostream& s, const rect_t& src)
{
return s << "{"
<< " t: " << src.top_m
<< ", l: " << src.left_m
<< ", b: " << src.bottom_m
<< ", r: " << src.right_m << ','
<< " h: " << src.height()
<< ", w: " << src.width()
<< " }";
}
rect_t scale_to_fit(const rect_t& src, const rect_t& dst)
{
float v_scale(src.height() / dst.height());
float h_scale(src.width() / dst.width());
float scale(std::max(v_scale, h_scale));
rect_t scale_rect(src / scale);
float v_offset((dst.width() - scale_rect.width()) / 2);
float h_offset((dst.height() - scale_rect.height()) / 2);
float new_top(dst.top_m + v_offset);
float new_left(dst.left_m + h_offset);
return rect_t{new_top,
new_left,
new_top + scale_rect.height(),
new_left + scale_rect.width()};
}
int main(int, char**)
{
std::cout << "Hello, world!\n";
rect_t dst{0, 0, 65, 120};
rect_t wide{0, 0, 75, 150};
rect_t tall{0, 0, 150, 75};
std::cout << "dst: " << dst << "\n";
std::cout << "wide: " << wide << "\n";
std::cout << "tall: " << tall << "\n";
rect_t wide_fit(scale_to_fit(wide, dst));
std::cout << "wide_fit: " << wide_fit << "\n";
rect_t tall_fit(scale_to_fit(tall, dst));
std::cout << "tall_fit: " << tall_fit << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment