I would like to give a detailed explanation, but for the time being the source code

```
package bezier
import (
"math"
)
type Point struct{
X,Y float64
}
// n! (factorial of n)
func factorial(n int)(int){
if n == 0{
return 1
}
return n * factorial(n-1)
}
func biCoe(n,i int)(float64){
return float64(factorial(n) / (factorial(n-i) * factorial(i)))
}
func bernstein(n,i int,t float64)(float64){
var N float64 = float64(n)
var I float64 = float64(i)
return biCoe(n,i) * math.Pow(t,I ) * math.Pow(1-t,N-I)
}
func BezierCurve(p []Point,t float64)(result Point){
for i,v := range p{
B := bernstein(len(p)-1,i,t)
result.X += v.X*B
result.Y += v.Y*B
}
return
}
//If the amount of change value is increased, a becomes a crisp curve.
func Curve(p []Point,a float64)(result []Point){
var t float64
for {
result = append(result, BezierCurve(p,t) )
t += a
if t >= 1{
break
}
}
return
}
```

Curve ([] Point, float64) is a function that gives the control point and the amount of change in t and returns a slice of P (t, 0> = t <= 1).

The user usually draws using this function (assuming that).

```
package bezier
import (
"testing"
"github.com/fogleman/gg"
)
func TestBezierCurve(t *testing.T){
//Control point
P := []Point{Point{10,10},Point{10,590},Point{590,590}}
//Amount of change
const A = 0.01
result := Curve(P,A)
dc := gg.NewContext(600,600)
dc.SetHexColor("#fff")
dc.Clear()
//Drawing control points
dc.Push()
dc.SetHexColor("#0000ff")
for _,v :=range P{
dc.DrawCircle(v.X,v.Y,4)
dc.Fill()
}
dc.Pop()
//Draw a curve
dc.Push()
dc.SetHexColor("#000")
//Move to the starting point
dc.MoveTo(P[0].X,P[0].Y)
for _,v :=range result{
dc.LineTo(v.X,v.Y)
}
dc.Stroke()
dc.Pop()
// P(t)Drawing of
dc.Push()
dc.SetHexColor("#f01000")
for _,v :=range result{
dc.DrawCircle(v.X,v.Y,3)
}
dc.Stroke()
dc.Pop()
dc.SavePNG("out.png ")
}
```

The blue point is the control point and the red is the circle centered on the coordinates of P (t).

I'm not good at mathematics, but I came up with an implementation in a few hours (too much time) by staring at mathematical formulas. There was a great sense of accomplishment. (Impression of elementary school students)

I would like to update it little by little when I am fine.

I hope this article will be useful to someone.

I am always indebted to http://github.com/fogleman/gg.

The article by @Rahariku was very helpful. Thank you very much.

Recommended Posts