calc_position.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package processing
  2. import (
  3. "math"
  4. "github.com/imgproxy/imgproxy/v3/imath"
  5. "github.com/imgproxy/imgproxy/v3/options"
  6. )
  7. func calcPosition(width, height, innerWidth, innerHeight int, gravity *options.GravityOptions, dpr float64, allowOverflow bool) (left, top int) {
  8. if gravity.Type == options.GravityFocusPoint {
  9. pointX := imath.ScaleToEven(width, gravity.X)
  10. pointY := imath.ScaleToEven(height, gravity.Y)
  11. left = pointX - innerWidth/2
  12. top = pointY - innerHeight/2
  13. } else {
  14. offX, offY := int(math.RoundToEven(gravity.X*dpr)), int(math.RoundToEven(gravity.Y*dpr))
  15. left = imath.ShrinkToEven(width-innerWidth+1, 2) + offX
  16. top = imath.ShrinkToEven(height-innerHeight+1, 2) + offY
  17. if gravity.Type == options.GravityNorth || gravity.Type == options.GravityNorthEast || gravity.Type == options.GravityNorthWest {
  18. top = 0 + offY
  19. }
  20. if gravity.Type == options.GravityEast || gravity.Type == options.GravityNorthEast || gravity.Type == options.GravitySouthEast {
  21. left = width - innerWidth - offX
  22. }
  23. if gravity.Type == options.GravitySouth || gravity.Type == options.GravitySouthEast || gravity.Type == options.GravitySouthWest {
  24. top = height - innerHeight - offY
  25. }
  26. if gravity.Type == options.GravityWest || gravity.Type == options.GravityNorthWest || gravity.Type == options.GravitySouthWest {
  27. left = 0 + offX
  28. }
  29. }
  30. var minX, maxX, minY, maxY int
  31. if allowOverflow {
  32. minX, maxX = -innerWidth+1, width-1
  33. minY, maxY = -innerHeight+1, height-1
  34. } else {
  35. minX, maxX = 0, width-innerWidth
  36. minY, maxY = 0, height-innerHeight
  37. }
  38. left = imath.Max(minX, imath.Min(left, maxX))
  39. top = imath.Max(minY, imath.Min(top, maxY))
  40. return
  41. }