When drawing graphs using PHP's GD library, developers sometimes need to draw polygons on images. Traditionally, the imageopenpolygon() function can draw a hollow polygon outline. But sometimes we want to use imagefilledpolygon() to achieve more flexible drawing effects, especially when we need to deal with color fills and outline styles. This article will introduce how to use imagefilledpolygon() instead of imageopenpolygon() and solve the problem of drawing hollow polygons.
imageopenpolygon() is mainly used to draw hollow polygons, and its effect is just strokes and no internal filling. imagefilledpolygon() can directly draw a filled polygon.
If you want to draw polygons with specific border colors or more complex controls, imagefilledpolygon() is more flexible. Especially when imageopenpolygon() does not support more diverse drawing requirements, using imagefilledpolygon() to simulate contour drawing by yourself will be a good alternative.
The basic idea is:
Use imagefilledpolygon() to draw a filled polygon (fill with background or transparent color).
Use imageline() to draw the border of a polygon separately.
This allows you to manually control the fill color and border color to achieve the desired hollow polygon effect.
Below is a complete example showing how to use imagefilledpolygon() to achieve an effect similar to imageopenpolygon() .
<?php
// Create a canvas
$image = imagecreatetruecolor(300, 300);
// Assign colors
$white = imagecolorallocate($image, 255, 255, 255);
$borderColor = imagecolorallocate($image, 0, 0, 0);
// Fill the background
imagefill($image, 0, 0, $white);
// Define the point of a polygon
$points = [
50, 50,
250, 70,
200, 200,
100, 250,
60, 150
];
// Fill polygons(Use background color,Keep the interior transparent or the same color)
imagefilledpolygon($image, $points, count($points) / 2, $white);
// Draw polygon borders
$num_points = count($points) / 2;
for ($i = 0; $i < $num_points; $i++) {
$x1 = $points[$i * 2];
$y1 = $points[$i * 2 + 1];
$x2 = $points[(($i + 1) % $num_points) * 2];
$y2 = $points[(($i + 1) % $num_points) * 2 + 1];
imageline($image, $x1, $y1, $x2, $y2, $borderColor);
}
// Output image
header('Content-Type: image/png');
imagepng($image);
// Free up resources
imagedestroy($image);
?>
imagefilledpolygon() fills with background color to prevent the internal area from discoloring.
Use the loop imageline() to manually connect each vertex to draw the outer border of the polygon.
($i + 1) % $num_points ensures that the last point can be connected to the first point.
If you want internal transparency, you can set a transparent background using imagesavealpha() and imagecolorallocatealpha() after creating the canvas.
If the background is not a solid color, you can adjust the fill color of imagefilledpolygon() appropriately, or do not fill directly, and draw the outline only by imageline() .