#ifndef SIZE_H #define SIZE_H #include "point.h" enum ESizeScaleMode { IGNORE_ASPECT_RATIO, KEEP_ASPECT_RATIO, KEEP_ASPECT_RATIO_BY_EXPANDING }; template class TSize { public: TSize() : wd(-1), ht(-1) {}; TSize(T width, T height) : wd(width), ht(height) { }; TSize(const TSize& other) : wd(other.wd), ht(other.ht) { }; TPoint toPoint() const { return TPoint(wd, ht); } bool isNull() const { return wd==0 && ht==0; } bool isEmpty() const { return wd<1 || ht<1; } bool isValid() const { return wd>=0 && ht>=0; } int width() const { return wd; } int height() const { return ht; } void setSize(T w, T h) { wd = w; ht = h; } void setWidth(T w) { wd = w; } void setHeight(T h) { ht = h; } TSize operator-() const { return TSize(-wd, -ht); } TSize operator+(const TSize& other) const { return TSize(wd + other.wd, ht + other.ht); } TSize& operator+=(const TSize& other) { wd+=other.wd; ht+=other.ht; return *this; } TSize operator-(const TSize& other) const { return TSize(wd - other.wd, ht - other.ht); } TSize& operator-=(const TSize& other) { wd-=other.wd; ht-=other.ht; return *this; } TSize operator*(const float v) const { return TSize((T)v*wd, (T)ht*v); } TSize& operator*=(const float v) { wd=(T)v*wd; ht=(T)ht*v; return *this; } TSize operator/(const float v) const { return TSize((T)wd/v, (T)ht/v); } TSize& operator/=(const float v) { (T)wd/=v; (T)ht/=v; return *this; } bool operator<=(const TSize&other) const { return wd<=other.wd || ht<=other.ht; } bool operator>=(const TSize&other) const { return wd>=other.wd || ht>=other.ht; } bool operator<(const TSize&other) const { return wd(const TSize&other) const { return wd>other.wd || ht>other.ht; } TSize& operator=(const TSize& other) { wd = other.wd; ht = other.ht; return *this; } bool operator==(const TSize& other) const { return other.wd==wd && other.ht==ht; } bool operator!=(const TSize& other) const { return other.wd!=wd || other.ht!=ht; } TSize expandedTo(const TSize& other) const { return TSize(std::max(wd,other.wd), std::max(ht,other.ht)); } TSize boundedTo(const TSize& other) const { return TSize(std::min(wd,other.wd), std::min(ht,other.ht)); } void scale(const TSize& s, ESizeScaleMode mode) { if(mode == IGNORE_ASPECT_RATIO || wd == 0 || ht == 0) { wd = s.wd; ht = s.ht; } else { bool useHeight; T rw = (s.ht * wd) / ht; if(mode == KEEP_ASPECT_RATIO) useHeight = (rw <= s.wd); else // mode == KEEP_ASPECT_RATIO_BY_EXPANDING useHeight = (rw >= s.wd); if(useHeight) { wd = rw; ht = s.ht; } else { ht = (s.wd * ht)/wd; wd = s.wd; } } } void scale(int w, int h, ESizeScaleMode mode) { scale(TSize(w, h)); } float ratio() const { return (float)wd/ht; } T area() const { return wd*ht; } private: T wd, ht; }; typedef TSize Size; typedef TSize SizeF; template std::ostream& operator<<(std::ostream& out, const TSize& size) { out << size.width() << " " << size.height(); return out; } template std::istream& operator>>(std::istream& in, TSize& size) { T w, h; in >> w >> h; size.setSize(w, h); return in; } #endif