【问题标题】:Imagick center text over image in specified areaImagick在指定区域的图像上居中文本
【发布时间】:2018-10-17 11:50:56
【问题描述】:

我正在使用 Imagick 库在图像上添加文本。 我在图像from x:280 to x:400 上定义了区域 我正在那个区域写文本,我想将该文本居中对齐,以下代码居中文本 x:1 和 x:400

$draw = new ImagickDraw();
$draw->setFillColor('white');
$draw->setFont($tffFile);

$draw->setTextAlignment(Imagick::ALIGN_CENTER);
$draw->setFontSize( 14 );
$image->annotateImage($draw, 280, 80, 0, 'Hey there');

【问题讨论】:

  • 能否添加您收到的任何错误?
  • 没有错误,但文本在整个图像中居中。我想在图像的特定区域居中文本

标签: php imagick


【解决方案1】:

为了使文本在感兴趣区域内居中,您将负责在应用Imagick::annotateImage 之前计算坐标。幸运的是,为此提供了Imagick::queryFontMetrics,正如您所观察到的,使用setTextAlignment 更有可能使事情复杂化,而不是帮助。

// Given a basic pseudo image.
$image = new Imagick();
$image->newPseudoImage(400, 400, 'PLASMA:');

// Let's define a ROI rectangle.
$rect = [
    'x' => 225,
    'y' => 225,
    'h' => 100,
    'w' => 100,
];

// Draw a Region-of-interest for reference.
$roi = new ImagickDraw();
$roi->setStrokeColor('RED');
$roi->setStrokeWidth(2);
$roi->setFillColor('TRANSPARENT');
$roi->rectangle($rect['x'],
                $rect['y'],
                $rect['x'] + $rect['w'],
                $rect['y'] + $rect['h']);
$image->drawImage($roi);

// Define your text-rendering context.
$ctx = new ImagickDraw();
$ctx->setFillColor('WHITE');
$ctx->setFontSize( 14 );

// Query who it will render with the image stack.
$metrics = $image->queryFontMetrics($ctx, 'Hey there');

// Adjust starting x,y as needed to meet your requirements.
$offset = [
    'x' => $rect['x'] + $rect['w'] / 2 - $metrics['textWidth'] / 2,
    'y' => $rect['y'] + $rect['h'] / 2 + $metrics['textHeight'] / 2 + $metrics['descender'],
];
// Draw text.
$image->annotateImage($ctx,
                      $offset['x'],
                      $offset['y'],
                      0,
                      'Hey there');
// Write to disk.
$image->writeImage('output.png');

自动换行和混合字体的内容变得有点复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2011-11-07
    • 1970-01-01
    • 2013-07-01
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多