/// <summary> /// Draw a line using Bresenhams line drawing algorithm. /// </summary> /// <remarks> /// Bresenhams line drawing algoritm: /// https://en.wikipedia.org/wiki/Bresenham's_line_algorithm /// C# Implementation: /// https://en.wikipedia.org/wiki/Bresenham's_line_algorithm /// </remarks> /// <param name="x0">Abscissa of the starting point of the line.</param> /// <param name="y0">Ordinate of the starting point of the line</param> /// <param name="x1">Abscissa of the end point of the line.</param> /// <param name="y1">Ordinate of the end point of the line</param> /// <param name="color">The color of the line.</param> public void DrawLine(int x0, int y0, int x1, int y1, Color color) { _display.SetPenColor(color); if (Stroke == 1) { DrawLine(x0, y0, x1, y1); return; } if (IsTallerThanWide(x0, y0, x1, y1)) { int xOffset = Stroke / 2; for (int i = 0; i < Stroke; i++) { DrawLine(x0 - xOffset + i, y0, x1 - xOffset + i, y1); } } else { int yOffset = Stroke / 2; for (int i = 0; i < Stroke; i++) { DrawLine(x0, y0 - yOffset + i, x1, y1 - yOffset + i); } } }
/// <summary> /// Draw a line using Bresenhams line drawing algorithm. /// </summary> /// <remarks> /// Bresenhams line drawing algoritm: /// https://en.wikipedia.org/wiki/Bresenham's_line_algorithm /// C# Implementation: /// https://en.wikipedia.org/wiki/Bresenham's_line_algorithm /// </remarks> /// <param name="x0">Abscissa of the starting point of the line.</param> /// <param name="y0">Ordinate of the starting point of the line</param> /// <param name="x1">Abscissa of the end point of the line.</param> /// <param name="y1">Ordinate of the end point of the line</param> /// <param name="color">The color of the line.</param> public void DrawLine(int x0, int y0, int x1, int y1, Color color) { _display.SetPenColor(color); var steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0); if (steep) { int t; t = x0; // swap x0 and y0 x0 = y0; y0 = t; t = x1; // swap x1 and y1 x1 = y1; y1 = t; } if (x0 > x1) { int t; t = x0; // swap x0 and x1 x0 = x1; x1 = t; t = y0; // swap y0 and y1 y0 = y1; y1 = t; } var dx = x1 - x0; var dy = Math.Abs(y1 - y0); var error = dx / 2; var ystep = y0 < y1 ? 1 : -1; var y = y0; for (var x = x0; x <= x1; x++) { DrawPixel(steep ? y : x, steep ? x : y); error = error - dy; if (error < 0) { y += ystep; error += dx; } } }