projector.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2011 The Graphics-Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package detect
  5. import (
  6. "image"
  7. )
  8. // projector allows projecting from a source Rectangle onto a target Rectangle.
  9. type projector struct {
  10. // rx, ry is the scaling factor.
  11. rx, ry float64
  12. // dx, dy is the translation factor.
  13. dx, dy float64
  14. // r is the clipping region of the target.
  15. r image.Rectangle
  16. }
  17. // newProjector creates a Projector with source src and target dst.
  18. func newProjector(dst image.Rectangle, src image.Rectangle) *projector {
  19. return &projector{
  20. rx: float64(dst.Dx()) / float64(src.Dx()),
  21. ry: float64(dst.Dy()) / float64(src.Dy()),
  22. dx: float64(dst.Min.X - src.Min.X),
  23. dy: float64(dst.Min.Y - src.Min.Y),
  24. r: dst,
  25. }
  26. }
  27. // pt projects p from the source rectangle onto the target rectangle.
  28. func (s *projector) pt(p image.Point) image.Point {
  29. return image.Point{
  30. clamp(s.rx*float64(p.X)+s.dx, s.r.Min.X, s.r.Max.X),
  31. clamp(s.ry*float64(p.Y)+s.dy, s.r.Min.Y, s.r.Max.Y),
  32. }
  33. }
  34. // rect projects r from the source rectangle onto the target rectangle.
  35. func (s *projector) rect(r image.Rectangle) image.Rectangle {
  36. return image.Rectangle{s.pt(r.Min), s.pt(r.Max)}
  37. }
  38. // clamp rounds and clamps o to the integer range [x0, x1].
  39. func clamp(o float64, x0, x1 int) int {
  40. x := int(o + 0.5)
  41. if x < x0 {
  42. return x0
  43. }
  44. if x > x1 {
  45. return x1
  46. }
  47. return x
  48. }