calc_position.go 1.5 KB

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