How to align text based on its box size using PHP Imagick? -
i'm puting texts in image @ specifics positions x , y. trying align text in box on photoshop, when use $draw->settextalignment() got different result. see bellow:
current result:
desired result:
the text , properties (font name, size, color, etc) dynamic, size can vary.
can me that?
code:
<?php $draw = new \imagickdraw(); $draw->setstrokecolor(new \imagickpixel('black')); $draw->setfillcolor(new \imagickpixel('red')); $draw->setstrokewidth(1); $draw->setfontsize(36); // first box $draw->settextalignment(\imagick::align_left); $draw->annotation(250, 75, "first line\nsecond line"); // second box $draw->settextalignment(\imagick::align_center); $draw->annotation(250, 210, "first line\nsecond line"); // third box $draw->settextalignment(\imagick::align_right); $draw->annotation(250, 330, "first line\nsecond line"); $draw->line(250, 0, 250, 500); $image = new \imagick(); $image->newimage(500, 500, new \imagickpixel('transparent')); $image->setimageformat("png"); $image->drawimage($draw); header("content-type: image/png"); echo $image->getimageblob();
p.s. vertical lines used on these examples show alignment differences.
i found solution! see result image , explanation:
we can query $draw
object using imagick::queryfontmetrics
in order know text width , height - returns other information's not needed purpose, see:
the x coordinate first argument of imagickdraw::annotation
, specifies text should drawn on horizontal axis of image.
with width of text in our hands (textwidth
) can can calculate correct x coordinate of text doing following each text alignment:
- left - use x coordinate - nothing do.
- center - sum x coordinate + half width of text.
- right - sum x coordinate + entire width of text.
see code in action:
<?php $image = new \imagick(); $draw = new \imagickdraw(); $draw->setstrokecolor(new \imagickpixel('black')); $draw->setfillcolor(new \imagickpixel('red')); $draw->setstrokewidth(1); $draw->setfontsize(36); $text = "first line\nsecond line"; // first box $draw->settextalignment(\imagick::align_left); $draw->annotation(250, 75, $text); // second box $draw->settextalignment(\imagick::align_center); $metrics = $image->queryfontmetrics($draw, $text); $draw->annotation(250 + ($metrics['textwidth'] / 2), 210, $text); // third box $draw->settextalignment(\imagick::align_right); $metrics = $image->queryfontmetrics($draw, $text); $draw->annotation(250 + ($metrics['textwidth']), 330, $text); $draw->line(250, 0, 250, 500); $image->newimage(500, 500, new \imagickpixel('transparent')); $image->setimageformat("png"); $image->drawimage($draw); header("content-type: image/png"); echo $image->getimageblob();
it outputs image texts aligned.
for more info see following references:
Comments
Post a Comment