2 回答

TA贡献1847条经验 获得超11个赞
正如我的评论中所述,您当前的代码只是在勾勒轮廓。这适用于绘制网格,但如果您希望向单元格添加一些文本,则必须手动绘制每个矩形,并使用这些坐标来放置文本。
使用imagettfbbox,您可以计算文本的宽度/高度,您需要该信息才能将文本“居中”到单元格中。
关于你的第二个问题,将总图片宽度除以你想要的单元格数,这样你就会知道每个单元格的大小。
我已经更新了您的代码以显示计算 x/y 坐标的一般思路
<?php
$imgpath = "duck.jpg";
$img = imagecreatefromjpeg($imgpath);
$size = getimagesize($imgpath);
$width = $size[0];
$height = $size[1];
$red = imagecolorallocate($img, 255, 0, 0);
// Number of cells
$xgrid = 5;
$ygrid = 5;
// Calulate each cell width/height
$xgridsize = $width / $xgrid;
$hgridsize = $height / $ygrid;
// Remember col
$c = 'A';
// Y
for ($j=0; $j < $ygrid; $j++) {
// X
for ($i=0; $i < $xgrid; $i++) {
// Dynamic x/y coords
$sy = $hgridsize * $j;
$sx = $xgridsize * $i;
// Draw rectangle
imagerectangle($img, $sx, $sy, $sx + $xgridsize, $sy + $hgridsize, $red);
// Draw text
addTextToCell($img, $sx, $xgridsize, $sy + $hgridsize, $hgridsize, $c . ($i + 1));
}
// Bumb cols
$c++;
}
function addTextToCell($img, $cellX, $cellWidth, $cellY, $cellHeight, $text) {
// Calculate text size
$text_box = imagettfbbox(20, 0, 'OpenSans', $text);
$text_width = $text_box[2]-$text_box[0];
$text_height = $text_box[7]-$text_box[1];
// Calculate x/y position
$textx = $cellX + ($cellWidth / 2) - $text_width;
$texty = $cellY - ($cellHeight / 2) - $text_height;
// Set color and draw
$color = imagecolorallocate($img, 0, 0, 255);
imagettftext($img, 20, 0, $textx, $texty, $color, 'OpenSans', $text);
}
// Save output as file
imagejpeg($img, 'output.jpg');
imagedestroy($img);
shell_exec('open -a Preview output.jpg');

TA贡献1776条经验 获得超12个赞
1)检查imagettftext()
和imagefttext()
功能。其中之一应该做你想做的。
2) 将输入图像的宽和高分别除以要划分的列数和行数,得到每个单元格的宽和高。
- 2 回答
- 0 关注
- 149 浏览
添加回答
举报