Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import copy
- class dimension:
- def __init__(self, a, b):
- self.a = a
- self.b = b
- def get_ratio(self):
- return self.a/self.b
- #scales this object so it fits into to_fit, maximizing size while keeping its ratio
- def scale_to_fit(self, to_fit):
- r = self.get_ratio()
- if r > to_fit.get_ratio(): # wider than to_fit -> fit width, scale height
- self.a, self.b = to_fit.a, to_fit.a/r
- else: # higher than to_fit -> fit height, scale width
- self.a, self.b = to_fit.b*r, to_fit.b
- #for test runs of dim.scale_to_fit
- def test(to_scale, to_fit):
- after_to_scale, after_to_fit = copy.copy(to_scale), copy.copy(to_fit)
- after_to_scale.scale_to_fit(after_to_fit)
- print("--- test run ---")
- print("to_fit dim: ", to_fit.a, to_fit.b)
- print("to_fit ratio:", to_fit.get_ratio())
- print("to_scale dim: ", to_scale.a, to_scale.b)
- print("to_scale ratio:", to_scale.get_ratio())
- print("new to_scale dim:", after_to_scale.a, after_to_scale.b)
- print("new to_scale ratio:", after_to_scale.get_ratio())
- assert to_fit.get_ratio() == to_fit.a / to_fit.b, "ratio calculation failed"
- assert after_to_fit.a == to_fit.a, "to_fit changed"
- assert after_to_fit.b == to_fit.b, "to_fit changed"
- assert math.isclose(after_to_scale.get_ratio(), to_scale.get_ratio(), rel_tol=1e-07), "to_scale ratio changed"
- if after_to_scale.get_ratio() > after_to_fit.get_ratio():
- assert after_to_scale.a == after_to_fit.a, "scaling failed"
- assert after_to_scale.b == after_to_fit.a / to_scale.get_ratio(), "scaling failed"
- else:
- assert after_to_scale.a == after_to_fit.b * to_scale.get_ratio(), "scaling failed"
- assert after_to_scale.b == after_to_fit.b, "scaling failed"
- if __name__ == "__main__":
- test(dimension(1600, 900), dimension(10, 30))
- test(dimension(1600, 900), dimension(30, 30))
- test(dimension(30, 10), dimension(1600, 900))
- test(dimension(10, 30), dimension(1600, 900))
Add Comment
Please, Sign In to add comment