php图片文字垂直对齐,PHP用Imagck实现图片文字水平以及垂直集中

$draw = new \ImagickDraw();

$imagick = new \Imagick();

$imagick->newImage($width, $height, new \ImagickPixel('none'));

$draw->setFillColor($color);

$draw->setFont($font_file);

$draw->setFontSize($size);

$draw->setTextEncoding('UTF-8');

$stringArr = $this->mbStringToArray($text);

$textHeight = 0;

$textWidth = 0;

$charCount = count($stringArr);

$texts = [];

foreach ($stringArr as $char) {

$metrics = $imagick->queryFontMetrics($draw, $char, true);

$charHeight = $metrics['textHeight'];

$charWidth = $metrics['textWidth'];

$textHeight += $charHeight;

$textWidth += $charWidth;

$texts[] = ['char' => $char, 'height' => $charHeight, 'width' => $charWidth];

}

if ($direction == 2) {

if ($charCount > 1) {

$textHeight += ($charCount - 1) * $space;

}

$draw->setTextAlignment(\Imagick::ALIGN_CENTER);

$x = $size / 2;

if ($textHeight > $height) {

$offset = 0;

} else {

$offset = ($height - $textHeight) / 2;

}

$y = $offset;

foreach ($texts as $c) {

$y += $c['height'];

$draw->annotation($x, $y, $c['char']);

$y += $space;

}

} else {

if ($charCount > 1) {

$textWidth += ($charCount - 1) * $space;

}

$metrics = $imagick->queryFontMetrics($draw, $text, false);

$y = $metrics['ascender'];

$draw->setTextAlignment(\Imagick::ALIGN_LEFT);

if ($align == \Imagick::ALIGN_CENTER) {

if ($textWidth > $width) {

$x = 0;

} else {

$x = ($width - $textWidth) / 2;

}

} elseif ($align == \Imagick::ALIGN_RIGHT) {

$x = $width - $textWidth;

} else {

$x = 0;

}

foreach ($texts as $c) {

$draw->annotation($x, $y, $c['char']);

$x += $c['width'] + $space;

}

}

$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");

echo $imagick->getImageBlob();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值