0

enter image description here

enter image description here

I have image area of 160px by 350px i need to be able to fit paragraphs of text in of different width and have font size go up or down automatically based on how much free space left in box.

I think this can be achieved with function Imagick::queryFontMetrics() that returns estimated text size without printing text as following array http://php.net/manual/en/imagick.queryfontmetrics.php

array (size=10)
  'characterWidth' => float 30
  'characterHeight' => float 30
  'ascender' => float 27
  'descender' => float -6
  'textWidth' => float 150
  'textHeight' => float 33
  'maxHorizontalAdvance' => float 60
  'boundingBox' => 
    array (size=4)
      'x1' => float 0
      'y1' => float 0
      'x2' => float 21.4375
      'y2' => float 22
  'originX' => float 151
  'originY' => float 0

What i need is formula to get out of data this function gives the best possible font size to fit green box.

Here's what i got so far, but i stuck at formula:

    $text_large = "Hello world Hello world";
    //$text_small = "Hello world Hello world Hello world Hello world Hello world";


    $img = new Imagick($path_to_image); //image 500 x 500
    $draw = new ImagickDraw();


    $draw->setFont("arial.ttf");
    $draw->setGravity(Imagick::GRAVITY_NORTHWEST);

    $draw->setFontSize(30); paragraph
    $fm = $img->queryFontMetrics($draw, $text_large, true);

    //this needs to be set automatically based on lenth of text
    $optimal_font_size = (160 / 2) - ($fm["textWidth"] / 2);



    $draw->setFontSize($optimal_font_size);
    $img->annotateImage($draw, 5, 50, null, $text_large);

    ...
Roman Toasov
  • 747
  • 11
  • 36
  • Is this what you need: http://stackoverflow.com/questions/5746537/how-can-i-wrap-text-using-imagick-in-php-so-that-it-is-drawn-as-multiline-text/5746551#5746551 ? – Danack Nov 23 '14 at 23:11
  • This one too, http://stackoverflow.com/questions/12231624/imagemagick-text-into-rectangle – Roman Toasov Nov 24 '14 at 08:01

1 Answers1

2

Simple solution was to tired yesterday to see.

$draw->setFontSize(15);
$metrics = $input_img->queryFontMetrics($draw, "Hello World Hello World Hello World", false);
$new_font_size = floor($metrics["characterWidth"] * 160 / $metrics["textWidth"]);
$draw->setFontSize($new_font_size);
$input_img->annotateImage($draw, 5, 50, null, "Hello World Hello World Hello World");
Roman Toasov
  • 747
  • 11
  • 36