Code Snippets #17 - DrawLine

Published 7/25/2013 by createdbyx in Code Snippets | Programming
Tags: ,

Source (converted from C) -> http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#C

```/// <summary>
/// Draws a line on an <see cref="GenericImage{T}"/>.
/// </summary>
/// <param name="image">
/// The destination image.
/// </param>
/// <param name="x1">
/// The x position for the start of the line.
/// </param>
/// <param name="y1">
/// The y position for the start of the line.
/// </param>
/// <param name="x2">
/// The x position for the end of the line.
/// </param>
/// <param name="y2">
/// The y position for the end of the line.
/// </param>
/// <param name="color">
/// The color that the line will be drawn with.
/// </param>
public static void DrawLine<T>(this GenericImage<T> image, int x1, int y1, int x2, int y2, T color)
{
// source (converted from C) -> http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#C
int dx = Math.Abs(x2 - x1), sx = x1 < x2 ? 1 : -1;
int dy = Math.Abs(y2 - y1), sy = y1 < y2 ? 1 : -1;
int err = (dx > dy ? dx : -dy) / 2;

for (; ; )
{
image[x1, y1] = color;
if (x1 == x2 && y1 == y2) break;
int e2 = err;
if (e2 > -dx) { err -= dy; x1 += sx; }
if (e2 < dy) { err += dx; y1 += sy; }
}
}```

• Comment
• Preview

Created by: X

Just another personal website in this crazy online world

 Dean Lunz (aka Created by: X) Computer programming nerd, and tech geek. About Me -- Resume