答案 0 :(得分:2)
您已经绘制了一个黑色10x10x10x140px
边框。在接下来的步骤中,您将必须实现类似于以下(伪代码)的算法:
// Calculate the maximum number of characters per line
max_line_chars := floor(width / character_width)
// Calculate the maximum number of lines that will fit the bottom area
max_lines := floor(bottom_black_area_height / character_height)
// Build an array of wrapped lines
lines = get_array_of_word_wrapped_lines(string, max_line_chars)
// Shrink `lines` to the size of maximum number of lines, if necessary
if length_of lines > max_lines then
lines := shrink(lines, max_lines)
height_offset := 0
else
height_offset := floor(((max_lines - length_of lines)) * character_height) / 2)
endif
for line in lines
line_width := character_width * length_of line
x := floor((image_width_with_borders - line_width) / 2)
y := floor(height_of_image + 2 * border_width + height_offset)
draw_line(x, y, line)
height_offset := height_offset + character_height
endfor
$add = 'test.jpg';
$string = 'My people will live in peaceful dwelling places, in secure homes, in undisturbed places of rest. Isaiah 32:17-18';
$string_len = strlen($string);
$split_words = false;
$im = imagecreatefromjpeg($add);
$width = imagesx($im);
$height = imagesy($im);
$border = 10;
$width_delta = 2 * $border;
$height_delta = 15 * $border;
$img_adj_width = $width + $width_delta;
$img_adj_height = $height + $height_delta;
$newimage = imagecreatetruecolor($img_adj_width, $img_adj_height);
$border_color = imagecolorallocate($newimage, 0, 0, 0);
imagefilledrectangle($newimage, 0, 0,
$img_adj_width, $img_adj_height, $border_color);
imagecopyresized($newimage, $im, $border, $border, 0, 0,
$width, $height, $width, $height);
$color = imagecolorallocate($newimage, 255, 255, 255);
$font = 4;
$font_width = imagefontwidth($font);
$font_height = imagefontheight($font);
$max_line_chars = floor($width / $font_width);
$max_lines = floor(($height_delta - 2 * $border) / $font_height);
$lines = explode(PHP_EOL, wordwrap($string, $max_line_chars, PHP_EOL, false));
if (count($lines) > $max_lines) {
$lines = array_slice($lines, 0, $max_lines);
$height_offset = 0;
} else {
$height_offset = floor((($max_lines - count($lines)) * $font_height) / 2);
}
foreach ($lines as $line) {
$line_width = $font_width * strlen($line);
$x = floor(($img_adj_width - $line_width) / 2);
$y = floor($height + $border * 2 + $height_offset);
imagestring($newimage, $font, $x, $y, $line, $color);
$height_offset += $font_height;
}
imagejpeg($newimage);
注意,wordwrap
函数以及substr
等标准字符串函数不支持Unicode!对于Unicode,您需要实现自己的wordwrap
版本,并使用multi-byte string functions代替。
示例输出
答案 1 :(得分:0)
将$position_middle
- 行更改为$position_middle = ceil(($height + ($text_height * 4.5)));
,看看是否能解决问题。