boxstuff.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. __version__='3.4.34'
  4. __doc__='''Utility functions to position and resize boxes within boxes'''
  5. def rectCorner(x, y, width, height, anchor='sw', dims=False):
  6. '''given rectangle controlled by x,y width and height return
  7. the corner corresponding to the anchor'''
  8. if anchor not in ('nw','w','sw'):
  9. if anchor in ('n','c','s'):
  10. x += width/2.
  11. else:
  12. x += width
  13. if anchor not in ('sw','s','se'):
  14. if anchor in ('w','c','e'):
  15. y += height/2.
  16. else:
  17. y += height
  18. return (x,y,width,height) if dims else (x,y)
  19. def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight,anchorAtXY=False):
  20. """This function helps position an image within a box.
  21. It first normalizes for two cases:
  22. - if the width is None, it assumes imWidth
  23. - ditto for height
  24. - if width or height is negative, it adjusts x or y and makes them positive
  25. Given
  26. (a) the enclosing box (defined by x,y,width,height where x,y is the \
  27. lower left corner) which you wish to position the image in, and
  28. (b) the image size (imWidth, imHeight), and
  29. (c) the 'anchor point' as a point of the compass - n,s,e,w,ne,se etc \
  30. and c for centre,
  31. this should return the position at which the image should be drawn,
  32. as well as a scale factor indicating what scaling has happened.
  33. It returns the parameters which would be used to draw the image
  34. without any adjustments:
  35. x,y, width, height, scale
  36. used in canvas.drawImage and drawInlineImage
  37. """
  38. scale = 1.0
  39. if width is None:
  40. width = imWidth
  41. if height is None:
  42. height = imHeight
  43. if width<0:
  44. width = -width
  45. x -= width
  46. if height<0:
  47. height = -height
  48. y -= height
  49. if preserve:
  50. imWidth = abs(imWidth)
  51. imHeight = abs(imHeight)
  52. scale = min(width/float(imWidth),height/float(imHeight))
  53. owidth = width
  54. oheight = height
  55. width = scale*imWidth-1e-8
  56. height = scale*imHeight-1e-8
  57. if not anchorAtXY:
  58. # if anchor not in ('nw','w','sw'):
  59. # dx = owidth-width
  60. # if anchor in ('n','c','s'):
  61. # x += dx/2.
  62. # else:
  63. # x += dx
  64. # if anchor not in ('sw','s','se'):
  65. # dy = oheight-height
  66. # if anchor in ('w','c','e'):
  67. # y += dy/2.
  68. # else:
  69. # y += dy
  70. x, y = rectCorner(x,y,owidth-width,oheight-height,anchor)
  71. if anchorAtXY:
  72. if anchor not in ('sw','s','se'):
  73. y -= height/2. if anchor in ('e','c','w') else height
  74. if anchor not in ('nw','w','sw'):
  75. x -= width/2. if anchor in ('n','c','s') else width
  76. return x,y, width, height, scale