add spiral square

This commit is contained in:
Yongwei Xing 2021-03-03 13:07:40 +08:00
parent a92fa10eb1
commit 3673852e35
2 changed files with 81 additions and 0 deletions

View file

@ -0,0 +1,20 @@
package main
import (
"generativeart"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
c := generativeart.NewCanva(500, 500, 2, 2)
c.SetBackground(generativeart.MistyRose)
c.SetLineWidth(10)
c.SetLineColor(generativeart.Orange)
c.SetColorSchema(generativeart.Plasma)
c.SetForeground(generativeart.Tomato)
c.FillBackground()
c.Draw(generativeart.NewSpiralSquare(40, 400, 0.05, true))
c.ToPNG("spiralsquare.png")
}

61
spiralsquare.go Normal file
View file

@ -0,0 +1,61 @@
package generativeart
import (
"github.com/fogleman/gg"
"math/rand"
)
type spiralSquare struct {
squareNum int
decay float64
rectSide float64
randColor bool
}
// NewSpiralSquare returns a spiralSquare object.
func NewSpiralSquare(squareNum int, rectSide, decay float64, randColor bool) *spiralSquare {
return &spiralSquare{
squareNum: squareNum,
decay: decay,
rectSide: rectSide,
randColor: randColor,
}
}
// Generative draws a spiral square images.
func (s *spiralSquare) Generative(c *canva) {
ctex := gg.NewContextForRGBA(c.img)
sl := s.rectSide
theta := rand.Intn(360) + 1
for i := 0; i < s.squareNum; i++ {
ctex.Push()
ctex.Translate(float64(c.width/2), float64(c.height/2))
ctex.Rotate(gg.Radians(float64(theta * (i + 1))))
ctex.Scale(sl, sl)
ctex.LineTo(-0.5, 0.5)
ctex.LineTo(0.5, 0.5)
ctex.LineTo(0.5, -0.5)
ctex.LineTo(-0.5, -0.5)
ctex.LineTo(-0.5, 0.5)
ctex.SetLineWidth(c.opts.lineWidth)
ctex.SetColor(c.opts.lineColor)
ctex.StrokePreserve()
if s.randColor {
ctex.SetColor(c.opts.colorSchema[rand.Intn(len(c.opts.colorSchema))])
} else {
ctex.SetColor(c.opts.foreground)
}
ctex.Fill()
ctex.Pop()
sl = sl - s.decay*s.rectSide
if sl < 0 {
return
}
}
}