我想用 GD 库用 PHP 在图像中画一条粗细的线。我在此页面PHP: imageline - Manual中找到了一些解决方案,但是当行的 (x, y) 位置发生变化时,它们似乎都不能正常工作。
我在页面中找到了 3 个功能
function dickelinie($img, $start_x, $start_y, $end_x, $end_y, $color, $thickness)
{
$angle = (atan2(($start_y - $end_y), ($end_x - $start_x)));
$dist_x = $thickness * (sin($angle));
$dist_y = $thickness * (cos($angle));
$p1x = ceil(($start_x + $dist_x));
$p1y = ceil(($start_y + $dist_y));
$p2x = ceil(($end_x + $dist_x));
$p2y = ceil(($end_y + $dist_y));
$p3x = ceil(($end_x - $dist_x));
$p3y = ceil(($end_y - $dist_y));
$p4x = ceil(($start_x - $dist_x));
$p4y = ceil(($start_y - $dist_y));
$array = array(0 => $p1x, $p1y, $p2x, $p2y, $p3x, $p3y, $p4x, $p4y);
imagefilledpolygon ($img, $array, (count($array) / 2), $color);
}
function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
if ($thick == 1)
{
return imageline($image, $x1, $y1, $x2, $y2, $color);
}
$t = $thick / 2 - 0.5;
if ($x1 == $x2 || $y1 == $y2)
{
return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
}
$k = ($y2 - $y1) / ($x2 - $x1);
$a = $t / sqrt(1 + pow($k, 2));
$points = array(
round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
);
imagefilledpolygon($image, $points, 4, $color);
return imagepolygon($image, $points, 4, $color);
}
function imagelinethick1($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
imagesetthickness($image, $thick);
imageline($image, $x1, $y1, $x2, $y2, $color);
}
我的测试用例是
header("Content-Type: image/png");
$image = @imagecreatetruecolor(500, 500) or die("Cannot initialize new GD image stream");
$color = imagecolorallocate($image, 255, 255, 255);
# Line thickness equals to 18 pixels
$thickness = 18;
# OK
dickelinie($image, 0, 0, 0, 500, $color, $thickness);
# Wrong: The thickness of the line is doubled
dickelinie($image, 200, 0, 200, 500, $color, $thickness);
# Wrong: The thickness of the line is halved
imagelinethick($image, 0, 0, 0, 500, $color, $thickness);
# OK
imagelinethick($image, 200, 0, 200, 500, $color, $thickness);
# Wrong: The thickness of the line is halved
imagelinethick1($image, 0, 0, 0, 500, $color, $thickness);
# OK
imagelinethick1($image, 200, 0, 200, 500, $color, $thickness);
imagepng($image);
imagedestroy($image);
谁能告诉我有什么问题吗?