Guest User

Untitled

a guest
Dec 14th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "image"
  5. "image/color"
  6. "image/draw"
  7. "image/png"
  8. "log"
  9. "math"
  10. "os"
  11. )
  12.  
  13. func main() {
  14. s := newState(6, 150, 42)
  15.  
  16. s.Set(color.RGBA{0, 255, 255, 255})
  17.  
  18. savePNG(s.image, "output.png")
  19. }
  20.  
  21. func newState(margin, radius, points int) *state {
  22. s := &state{
  23. theta: (math.Pi * 2) / float64(points),
  24. image: uniformImage((margin+radius)*2, (margin+radius)*2, color.Black),
  25. offset: image.Point{X: margin + radius, Y: margin + radius},
  26. }
  27.  
  28. for n := 0; n < points; n++ {
  29. s.AddPoint(float64(radius), n)
  30. }
  31.  
  32. return s
  33. }
  34.  
  35. type state struct {
  36. theta float64
  37. image *image.RGBA
  38. offset image.Point
  39. points []image.Point
  40. }
  41.  
  42. func (s *state) AddPoint(r float64, n int) {
  43. angle := s.theta * float64(n)
  44.  
  45. s.add(image.Point{
  46. X: s.offset.X + int(r*math.Cos(angle)),
  47. Y: s.offset.Y + int(r*math.Sin(angle)),
  48. })
  49. }
  50.  
  51. func (s *state) add(p image.Point) {
  52. s.points = append(s.points, p)
  53. }
  54.  
  55. func (s *state) Set(c color.Color) {
  56. for _, p := range s.points {
  57. s.image.Set(p.X, p.Y, c)
  58. s.image.Set(p.X+1, p.Y, c)
  59. s.image.Set(p.X+1, p.Y+1, c)
  60. }
  61. }
  62.  
  63. func uniformImage(w, h int, c color.Color) *image.RGBA {
  64. m := image.NewRGBA(image.Rect(0, 0, w, h))
  65.  
  66. draw.Draw(m, m.Bounds(), &image.Uniform{c}, image.ZP, draw.Src)
  67.  
  68. return m
  69. }
  70.  
  71. func savePNG(m image.Image, fn string) {
  72. if f, err := os.Create(fn); err != nil {
  73. log.Printf("unable to create %s: %v", fn, err)
  74. } else {
  75. defer f.Close()
  76. enc := png.Encoder{
  77. CompressionLevel: png.BestCompression,
  78. }
  79. enc.Encode(f, m)
  80. }
  81. }
Add Comment
Please, Sign In to add comment