github.com/aloncn/graphics-go@v0.0.1/graphics/detect/projector.go (about) 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 5 package detect 6 7 import ( 8 "image" 9 ) 10 11 // projector allows projecting from a source Rectangle onto a target Rectangle. 12 type projector struct { 13 // rx, ry is the scaling factor. 14 rx, ry float64 15 // dx, dy is the translation factor. 16 dx, dy float64 17 // r is the clipping region of the target. 18 r image.Rectangle 19 } 20 21 // newProjector creates a Projector with source src and target dst. 22 func newProjector(dst image.Rectangle, src image.Rectangle) *projector { 23 return &projector{ 24 rx: float64(dst.Dx()) / float64(src.Dx()), 25 ry: float64(dst.Dy()) / float64(src.Dy()), 26 dx: float64(dst.Min.X - src.Min.X), 27 dy: float64(dst.Min.Y - src.Min.Y), 28 r: dst, 29 } 30 } 31 32 // pt projects p from the source rectangle onto the target rectangle. 33 func (s *projector) pt(p image.Point) image.Point { 34 return image.Point{ 35 clamp(s.rx*float64(p.X)+s.dx, s.r.Min.X, s.r.Max.X), 36 clamp(s.ry*float64(p.Y)+s.dy, s.r.Min.Y, s.r.Max.Y), 37 } 38 } 39 40 // rect projects r from the source rectangle onto the target rectangle. 41 func (s *projector) rect(r image.Rectangle) image.Rectangle { 42 return image.Rectangle{s.pt(r.Min), s.pt(r.Max)} 43 } 44 45 // clamp rounds and clamps o to the integer range [x0, x1]. 46 func clamp(o float64, x0, x1 int) int { 47 x := int(o + 0.5) 48 if x < x0 { 49 return x0 50 } 51 if x > x1 { 52 return x1 53 } 54 return x 55 }