Page 1 of 1

measuring string size for Annotate()

Posted: 2014-09-11T13:23:30-07:00
by danmc
Is there a way to figure out if text added via Annotate() got cut off when added to a background of a fixed size? Alternatively is there a way to figure out how much room will be needed for text? I have something like the following but in some cases the string stored in $names is too big and I either need to automatically adjust the font size or at least log a warning at the program output.

Thanks
-Dan

Code: Select all

my $text_back = Image::Magick->new();
my $x = $text_back->ReadImage('xc:white');
warn "$x" if "$x";

my $my_h = 150;
my $my_w = 600;

print "[$my_w x $my_h] ...";
$text_back->Resize(width=>$my_w, height=>$my_h);

# code here to read $names out of a file.  It may be
# a couple of lines long

print "Adding label...";
$text_back->Annotate(undercolor=>'white',
                       font=>'LCALLIG.TTF',
                       pointsize=>36,
                       fill=>'black',
                       gravity=>'Center',
                       text=>$names);

Re: measuring string size for Annotate()

Posted: 2014-09-11T14:00:06-07:00
by fmw42

Re: measuring string size for Annotate()

Posted: 2014-09-11T14:33:12-07:00
by snibgo
My general technique for this is to annotate to an area larger than required, and see if that larger area was needed. (In most cases, this means trimming it, and ensuring this is smaller in both dimensions than the required area.)

Re: measuring string size for Annotate()

Posted: 2014-09-13T08:59:37-07:00
by danmc
This seemed to do the trick. Then I was able to scale the font, if needed, for the Annotate() call.

Code: Select all


  print "Checking label size...";
  my ($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance)
    = $text_back->QueryMultilineFontMetrics(
                                            undercolor=>'white',
                                            font=>$font_file,
                                            pointsize=>$font_size, 
                                            fill=>'black', 
                                            gravity=>'Center',
                                            text=>$names
                                           );
  print "[$width x $height] vs [$my_w x $my_h]...";