Introduction Lines Circles Sharp Waves Curly Waves Colors Lines Between Two Points Arcs Between Two Points

Lines - Maths317

Vertical Lines

To draw a vertical line, keep X coordinate constant and vary the Y Coordinate. This can be done with a for loop.

Horizontal Lines

To draw a horizontal line, keep Y coordinate constant and vary the X Coordinate. This can be done with a for loop.

Bent Lines having a Source Coordinate and an Angle

To calculate the second point of a line given the initial coordinates \((x_0, y_0)\), the angle \(\theta\) and the length l, use the two formulas below:

\(x_1 = x_0 + (l \times cos\theta) \)
\(y_1 = y_0 + (l \times sin\theta) \)

Now to get all the points for drawing use the formulas above with lengths of one and iterate for the length of the line

Test Code


package main

import (
  "github.com/disintegration/imaging"
  "image/color"
  "math"
)

func main() {
  img := imaging.New(500, 300, color.White)

  lengthOfLine := 200
  angle := 80
  x0 := 20
  y0 := 50
  // using increments of 1
  var x, y float64
  angleInRadians := float64(angle) * (math.Pi / 180)

  x = float64(x0)
  y = float64(y0)

  for i := 1; i < lengthOfLine; i++ {
    x1 := x + (math.Cos(angleInRadians) * 1)
    y1 := y + (math.Sin(angleInRadians) * 1)

    img.Set(int(math.Round(x1)), int(math.Round(y1)), color.Black)

    x = x1
    y = y1
  }

  err := imaging.Save(img, "out_line1.png")
  if err != nil {
    panic(err)
  }
}

Note that the math functions in golang expects the angles in radians which was converted with the formula:

\(R = \theta {pi \over 180} \)
< Previous Next >