geomutils.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. __version__='3.3.0'
  4. __doc__='''Utility functions for geometrical operations.'''
  5. def normalizeTRBL(p):
  6. '''
  7. Useful for interpreting short descriptions of paddings, borders, margin, etc.
  8. Expects a single value or a tuple of length 2 to 4.
  9. Returns a tuple representing (clockwise) the value(s) applied to the 4 sides of a rectangle:
  10. If a single value is given, that value is applied to all four sides.
  11. If two or three values are given, the missing values are taken from the opposite side(s).
  12. If four values are given they are returned unchanged.
  13. >>> normalizeTRBL(1)
  14. (1, 1, 1, 1)
  15. >>> normalizeTRBL((1, 1.2))
  16. (1, 1.2, 1, 1.2)
  17. >>> normalizeTRBL((1, 1.2, 0))
  18. (1, 1.2, 0, 1.2)
  19. >>> normalizeTRBL((1, 1.2, 0, 8))
  20. (1, 1.2, 0, 8)
  21. '''
  22. if not isinstance(p, (tuple, list)):
  23. return (p,)*4
  24. elif len(p)==1:
  25. return (p[0],)*4
  26. l = len(p)
  27. if l < 2 or l > 4:
  28. raise ValueError('A padding must have between 2 and 4 values but got %d.' % l)
  29. return tuple(p) + tuple([ p[i-2] for i in range(l, 4) ])