绘制图形和文字

1.绘制图形

我们要想在画布上绘制图形我们可以用imagesetpixel() 绘制一个点

imagesetpixel---画一个单一像素也就是画一个点

语法结构为bool imagesetpixel  ( resource $image  , int $x  , int $y  , int $color  )

imagesetpixel()  在 image  图像中用 color  颜色在 x , y  坐标(图像左上角为 0,0)上画一个点。

我们先给点创建一个颜色

$color = imagecolorallocate($img,0,0,0);

 在绘制出来

imagesetpixel($img,100,50,$color);

然后我们在画布上随机画10个点,代码如下 

$color = imagecolorallocate($img,0,0,0);
//随机画10个点
for($i=0;$i<10;$i++){
	$x=rand(0,200);
	$y=rand(0,100);
	imagesetpixel($img,$x,$y,$color);
}

 我们也可以在画布上绘制图形我们可以用imageline()  绘制一个线段

语法结构为  bool imageline  ( resource $image  , int $x1  , int $y1  , int $x2  , int $y2  , int $color  )

imageline()  用 color  颜色在图像 image  中从坐标 x1 , y1  到 x2 , y2 (图像左上角为 0, 0)画一条线段。

我们还是先给线段创建一个颜色

$color = imagecolorallocate($img,0,0,255);

 然后我们从左上角画到右下角

imageline($img,0,0,200,100,$color);

当然我们也可以随机画几条斜线

//随机画10条线
$color = imagecolorallocate($img,0,0,255);
for($i=0;$i<10;$i++){
	$x1=rand(0,200);
	$y1=rand(0,100);
	$x2=rand(0,200);
	$y2=rand(0,100);
	imageline($img,$x1,$y1,$x2,$y2,$color);
}

 我们还可以画一个矩形用imagerectangle() 

语法结构为   bool imagerectangle  ( resource $image  , int $x1  , int $y1  , int $x2  , int $y2  , int $col  )

imagerectangle()  用 col  颜色在 image  图像中画一个矩形,其左上角坐标为 x1, y1,右下角坐标为 x2, y2。图像的左上角坐标为 0, 0。

//画一个矩形
$color = imagecolorallocate($img,0,255,0);
imagerectangle($img,50,50,100,100,$color);

我们还可以用imagefilledrectangle() 来画一个矩形

语法结构为  bool imagefilledrectangle  ( resource $image  , int $x1  , int $y1  , int $x2  , int $y2  , int $color  )

imagefilledrectangle()  在 image  图像中画一个用 color  颜色填充了的矩形,其左上角坐标为 x1 , y1 ,右下角坐标为 x2 , y2 。0, 0 是图像的最左上角。

//画一个矩形
$color = imagecolorallocate($img,0,255,0);
imagefilledrectangle($img,50,50,100,100,$color);

这两者的区别就是一个会填充颜色,一个不会

2.绘制文字

绘制文字我们使用imagettftext 

语法结构为   array imagettftext  ( resource $image  , float $size  , float $angle  , int $x  , int $y  , int $color  , string $fontfile  , string $text  )

各个参数分别为

size   :字体的尺寸。根据 GD 的版本,为像素尺寸(GD1)或点(磅)尺寸(GD2)。

angle   :角度制表示的角度,0 度为从左向右读的文本。更高数值表示逆时针旋转。例如 90 度表示从下向上读的文本。

i$x , $y:由 x , y  所表示的坐标定义了第一个字符的基本点(大概是字符的左下角)。

color   :颜色索引

fontfile   :是想要使用的 TrueType 字体的路径。(也就是字体库,我们可以在c盘的windows中fonts中找到simsunb.ttc)

text   :UTF-8 编码的文本字符串。

//输出文字
$text="hello";
$color=imagecolorallocate($img,255,255,0);
$font = "simsun.ttf";
imagettftext($img,20,0,10,50,$color,$font,$text);

猜你喜欢

转载自blog.csdn.net/qq_42402975/article/details/84401261