From 3673852e355651c095027422918a72a8aeda7e33 Mon Sep 17 00:00:00 2001 From: Yongwei Xing Date: Wed, 3 Mar 2021 13:07:40 +0800 Subject: [PATCH] add spiral square --- example/example_spiralsquare.go | 20 +++++++++++ spiralsquare.go | 61 +++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 example/example_spiralsquare.go create mode 100644 spiralsquare.go diff --git a/example/example_spiralsquare.go b/example/example_spiralsquare.go new file mode 100644 index 0000000..6b19dd2 --- /dev/null +++ b/example/example_spiralsquare.go @@ -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") +} diff --git a/spiralsquare.go b/spiralsquare.go new file mode 100644 index 0000000..4cc4ff2 --- /dev/null +++ b/spiralsquare.go @@ -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 + } + } +}