MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / drawLine

Method drawLine

src/main/java/com/thealgorithms/geometry/WusLine.java:88–133  ·  view source on GitHub ↗

Draws an anti-aliased line using Wu's algorithm. The algorithm produces smooth lines by drawing pairs of pixels at each x-coordinate (or y-coordinate for steep lines), with intensities based on the line's distance from pixel centers. @param x0 the x-coordinate of the line's start point @param y0 t

(int x0, int y0, int x1, int y1)

Source from the content-addressed store, hash-verified

86 * ordered from start to end
87 */
88 public static List<Pixel> drawLine(int x0, int y0, int x1, int y1) {
89 List<Pixel> pixels = new ArrayList<>();
90
91 // Determine if the line is steep (more vertical than horizontal)
92 boolean steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);
93
94 if (steep) {
95 // For steep lines, swap x and y coordinates to iterate along y-axis
96 int temp = x0;
97 x0 = y0;
98 y0 = temp;
99
100 temp = x1;
101 x1 = y1;
102 y1 = temp;
103 }
104
105 if (x0 > x1) {
106 // Ensure we always draw from left to right
107 int temp = x0;
108 x0 = x1;
109 x1 = temp;
110
111 temp = y0;
112 y0 = y1;
113 y1 = temp;
114 }
115
116 // Calculate the line's slope
117 double deltaX = x1 - (double) x0;
118 double deltaY = y1 - (double) y0;
119 double gradient = (deltaX == 0) ? 1.0 : deltaY / deltaX;
120
121 // Process the first endpoint
122 EndpointData firstEndpoint = processEndpoint(x0, y0, gradient, true);
123 addEndpointPixels(pixels, firstEndpoint, steep);
124
125 // Process the second endpoint
126 EndpointData secondEndpoint = processEndpoint(x1, y1, gradient, false);
127 addEndpointPixels(pixels, secondEndpoint, steep);
128
129 // Draw the main line between endpoints
130 drawMainLine(pixels, firstEndpoint, secondEndpoint, gradient, steep);
131
132 return pixels;
133 }
134
135 /**
136 * Processes a line endpoint to determine its pixel coordinates and intensities.

Calls 4

processEndpointMethod · 0.95
addEndpointPixelsMethod · 0.95
drawMainLineMethod · 0.95
absMethod · 0.45