php draw line pixel

Solutions on MaxInterview for php draw line pixel by the best coders in the world

showing results for - "php draw line pixel"
Elena
31 Apr 2020
1/**
2  * Draw a line using Bresenham's line algorithm.
3  *
4  * @param resource $im
5  *   The image resource.
6  * @param int $x0
7  *   The x part of the starting coordinate.
8  * @param int $y0
9  *   The y part of the starting coordinate.
10  * @param int $x1
11  *   The x part of the ending coordinate.
12  * @param int $y1
13  *   The y part of the ending coordinate.
14  * @param int $color
15  *   The color of the line, created from imagecolorallocate().
16  */
17function drawLine($im, $x0, $y0, $x1, $y1, $color) {
18  if ($x0 == $x1 && $y0 == $y1) {
19    // Start and finish are the same.
20    imagesetpixel($im, $x0, $y0, $color);
21    return;
22  }
23
24  $dx = $x1 - $x0;
25  if ($dx < 0) {
26    // x1 is lower than x0.
27    $sx = -1;
28  } else {
29    // x1 is higher than x0.
30    $sx = 1;
31  }
32
33  $dy = $y1 - $y0;
34  if ($dy < 0) {
35    // y1 is lower than y0.
36    $sy = -1;
37  } else {
38    // y1 is higher than y0.
39    $sy = 1;
40  }
41
42  if (abs($dy) < abs($dx)) {
43    // Slope is going downwards.
44    $slope = $dy / $dx;
45    $pitch = $y0 - $slope * $x0;
46
47    while ($x0 != $x1) {
48      imagesetpixel($im, $x0, round($slope * $x0 + $pitch), $color);
49      $x0 += $sx;
50    }
51  } else {
52    // Slope is going upwards.
53    $slope = $dx / $dy;
54    $pitch = $x0 - $slope * $y0;
55
56    while ($y0 != $y1) {
57      imagesetpixel($im, round($slope * $y0 + $pitch), $y0, $color);
58      $y0 += $sy;
59    }
60  }
61
62  // Finish by adding the final pixel.
63  imagesetpixel($im, $x1, $y1, $color);
64}
similar questions
queries leading to this page
php draw line pixel