translate.go 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package transform
  2. import (
  3. "image"
  4. "github.com/anthonynsimon/bild/clone"
  5. "github.com/anthonynsimon/bild/parallel"
  6. )
  7. // Translate repositions a copy of the provided image by dx on the x-axis and
  8. // by dy on the y-axis and returns the result. The bounds from the provided image
  9. // will be kept.
  10. // A positive dx value moves the image towards the right and a positive dy value
  11. // moves the image upwards.
  12. func Translate(img image.Image, dx, dy int) *image.RGBA {
  13. src := clone.AsShallowRGBA(img)
  14. if dx == 0 && dy == 0 {
  15. return src
  16. }
  17. w, h := src.Bounds().Dx(), src.Bounds().Dy()
  18. dst := image.NewRGBA(src.Bounds())
  19. parallel.Line(h, func(start, end int) {
  20. for y := start; y < end; y++ {
  21. for x := 0; x < w; x++ {
  22. ix, iy := x-dx, y+dy
  23. if ix < 0 || ix >= w || iy < 0 || iy >= h {
  24. continue
  25. }
  26. srcPos := iy*src.Stride + ix*4
  27. dstPos := y*src.Stride + x*4
  28. copy(dst.Pix[dstPos:dstPos+4], src.Pix[srcPos:srcPos+4])
  29. }
  30. }
  31. })
  32. return dst
  33. }