scale.go 1020 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package image
  2. type Scale struct {
  3. Width uint
  4. Height uint
  5. Scale float64
  6. }
  7. func NewScale(width uint, height uint, scale float64) *Scale {
  8. return &Scale{width, height, scale}
  9. }
  10. // MinRatio 获取缩放比例,等比缩放,以短边为准
  11. func (s Scale) MinRatio(width, height uint) Scale {
  12. scale := 1.0
  13. if s.Width/s.Height > width/height {
  14. if s.Height > height {
  15. scale = CustomScale(height, s.Height)
  16. }
  17. } else {
  18. if s.Width > width {
  19. scale = CustomScale(width, s.Width)
  20. }
  21. }
  22. width = uint(scale * float64(s.Width))
  23. height = uint(scale * float64(s.Height))
  24. return Scale{Width: width, Height: height, Scale: scale}
  25. }
  26. // MaxRatio 裁切,以长边为准
  27. func (s Scale) MaxRatio(width, height uint) Scale {
  28. scale := 1.0
  29. if s.Width/s.Height > width/height {
  30. scale = CustomScale(height, s.Height)
  31. } else {
  32. scale = CustomScale(width, s.Width)
  33. }
  34. width = uint(scale * float64(s.Width))
  35. height = uint(scale * float64(s.Height))
  36. return Scale{Width: width, Height: height, Scale: scale}
  37. }