7 $VERSION = sprintf "%d.%03d", q$Revision$=~/\d+/g;
9 # the aim here is that we can:
10 # - add file based types in one place: here
11 # - make sure we only attempt to create types that exist
12 # - give reasonable defaults
13 # - give the user some control over which types get used
17 class=>'Imager::Font::Truetype',
18 module=>'Imager/Font/Truetype.pm',
22 class=>'Imager::Font::Type1',
23 module=>'Imager/Font/Type1.pm',
27 class=>'Imager::Font::FreeType2',
28 module=>'Imager/Font/FreeType2.pm',
29 files=>'.*\.(pfa|pfb|otf|ttf|fon|fnt|dfont|pcf(\.gz)?)$',
32 class=>'Imager::Font::Image',
33 module=>'Imager/Font/Image.pm',
37 class=>'Imager::Font::Win32',
38 module=>'Imager/Font/Win32.pm',
42 # this currently should only contain file based types, don't add w32
43 my @priority = qw(t1 tt ft2 ifs);
45 # when Imager::Font is loaded, Imager.xs has not been bootstrapped yet
46 # this function is called from Imager.pm to finish initialization
48 @priority = grep Imager::i_has_format($_), @priority;
49 delete @drivers{grep !Imager::i_has_format($_), keys %drivers};
53 # 1. start by checking if file is the parameter
54 # 1a. if so qualify path and compare to the cache.
55 # 2a. if in cache - take it's id from there and increment count.
61 my ($file, $type, $id);
62 my %hsh=(color => Imager::Color->new(255,0,0,0),
70 if ( $file !~ m/^\// ) {
73 $Imager::ERRSTR = "Font $file not found";
79 if (!defined($type) or !$drivers{$type}) {
80 for my $drv (@priority) {
82 my $re = $drivers{$drv}{files} or next;
83 if ($file =~ /$re/i) {
89 if (!defined($type)) {
90 $Imager::ERRSTR = "Font type not found";
93 } elsif ($hsh{face}) {
96 $Imager::ERRSTR="No font file specified";
100 if (!$Imager::formats{$type}) {
101 $Imager::ERRSTR = "`$type' not enabled";
105 # here we should have the font type or be dead already.
107 require $drivers{$type}{module};
108 return $drivers{$type}{class}->new(%hsh);
111 # returns first defined parameter
114 return $_ if defined $_;
121 my %input = ('x' => 0, 'y' => 0, @_);
122 unless ($input{image}) {
123 $Imager::ERRSTR = 'No image supplied to $font->draw()';
126 $input{string} = _first($input{string}, $input{text});
127 unless (defined $input{string}) {
128 $Imager::ERRSTR = "Missing required parameter 'string'";
131 $input{aa} = _first($input{aa}, $input{antialias}, $self->{aa}, 1);
132 # the original draw code worked this out but didn't use it
133 $input{align} = _first($input{align}, $self->{align});
134 $input{color} = _first($input{color}, $self->{color});
135 $input{color} = Imager::_color($input{'color'});
137 $input{size} = _first($input{size}, $self->{size});
138 unless (defined $input{size}) {
139 $input{image}{ERRSTR} = "No font size provided";
142 $input{align} = _first($input{align}, 1);
143 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
144 $input{vlayout} = _first($input{vlayout}, $self->{vlayout}, 0);
146 $self->_draw(%input);
151 my %input = ( halign => 'left', valign => 'baseline',
152 'x' => 0, 'y' => 0, @_ );
154 my $text = _first($input{string}, $input{text});
155 unless (defined $text) {
156 Imager->_set_error("Missing required parameter 'string'");
160 # image needs to be supplied, but can be supplied as undef
161 unless (exists $input{image}) {
162 Imager->_set_error("Missing required parameter 'image'");
165 my $size = _first($input{size}, $self->{size});
166 my $utf8 = _first($input{utf8}, 0);
168 my $bbox = $self->bounding_box(string=>$text, size=>$size, utf8=>$utf8);
169 my $valign = $input{valign};
171 unless $valign && $valign =~ /^(?:top|center|bottom|baseline)$/;
173 my $halign = $input{halign};
175 unless $halign && $halign =~ /^(?:left|start|center|end|right)$/;
180 if ($valign eq 'top') {
183 elsif ($valign eq 'center') {
184 $y += $bbox->ascent - $bbox->text_height / 2;
186 elsif ($valign eq 'bottom') {
187 $y += $bbox->descent;
189 # else baseline is the default
191 if ($halign eq 'left') {
192 $x -= $bbox->start_offset;
194 elsif ($halign eq 'start') {
197 elsif ($halign eq 'center') {
198 $x -= $bbox->start_offset + $bbox->total_width / 2;
200 elsif ($halign eq 'end' || $halign eq 'right') {
201 $x -= $bbox->start_offset + $bbox->total_width - 1;
207 delete @input{qw/x y/};
208 $self->draw(%input, 'x' => $x, 'y' => $y, align=>1)
210 # for my $i (1 .. length $text) {
211 # my $work = substr($text, 0, $i);
212 # my $bbox = $self->bounding_box(string=>$work, size=>$size, utf8=>$utf8);
213 # my $nx = $x + $bbox->end_offset;
214 # $input{image}->setpixel(x=>[ ($nx) x 5 ],
215 # 'y'=>[ $y-2, $y-1, $y, $y+1, $y+2 ],
220 return ($x+$bbox->start_offset, $y-$bbox->ascent,
221 $x+$bbox->end_offset, $y-$bbox->descent+1);
228 if (!exists $input{'string'}) {
229 $Imager::ERRSTR='string parameter missing';
232 $input{size} ||= $self->{size};
233 $input{sizew} = _first($input{sizew}, $self->{sizew}, 0);
234 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
236 my @box = $self->_bounding_box(%input);
239 if(@box && exists $input{'x'} and exists $input{'y'}) {
240 my($gdescent, $gascent)=@box[1,3];
241 $box[1]=$input{'y'}-$gascent; # top = base - ascent (Y is down)
242 $box[3]=$input{'y'}-$gdescent; # bottom = base - descent (Y is down, descent is negative)
243 $box[0]+=$input{'x'};
244 $box[2]+=$input{'x'};
245 } elsif (@box && $input{'canon'}) {
246 $box[3]-=$box[1]; # make it cannoical (ie (0,0) - (width, height))
252 require Imager::Font::BBox;
254 return Imager::Font::BBox->new(@box);
261 # I'm assuming a default of 72 dpi
264 $Imager::ERRSTR = "Setting dpi not implemented for this font type";
276 # this is split into transform() and _transform() so we can
277 # implement other tags like: degrees=>12, which would build a
278 # 12 degree rotation matrix
279 # but I'll do that later
280 unless ($hsh{matrix}) {
281 $Imager::ERRSTR = "You need to supply a matrix";
285 return $self->_transform(%hsh);
289 $Imager::ERRSTR = "This type of font cannot be transformed";
302 @priority = grep Imager::i_has_format($_), @_;
313 Imager::Font - Font handling for Imager.
317 $t1font = Imager::Font->new(file => 'pathtofont.pfb');
318 $ttfont = Imager::Font->new(file => 'pathtofont.ttf');
319 $w32font = Imager::Font->new(face => 'Times New Roman');
321 $blue = Imager::Color->new("#0000FF");
322 $font = Imager::Font->new(file => 'pathtofont.ttf',
333 $right_bearing) = $font->bounding_box(string=>"Foo");
335 $logo = $font->logo(text => "Slartibartfast Enterprises",
339 # logo is proposed - doesn't exist yet
342 $img->string(font => $font,
350 # Documentation in Imager.pm
354 This module handles creating Font objects used by imager. The module
355 also handles querying fonts for sizes and such. If both T1lib and
356 freetype were avaliable at the time of compilation then Imager should
357 be able to work with both truetype fonts and t1 postscript fonts. To
358 check if Imager is t1 or truetype capable you can use something like
362 print "Has truetype" if $Imager::formats{tt};
363 print "Has t1 postscript" if $Imager::formats{t1};
364 print "Has Win32 fonts" if $Imager::formats{w32};
365 print "Has Freetype2" if $Imager::formats{ft2};
371 This creates a font object to pass to functions that take a font argument.
373 $font = Imager::Font->new(file => 'denmark.ttf',
379 This creates a font which is the truetype font denmark.ttf. It's
380 default color is $blue, default size is 30 pixels and it's rendered
381 antialised by default. Imager can see which type of font a file is by
382 looking at the suffix of the filename for the font. A suffix of 'ttf'
383 is taken to mean a truetype font while a suffix of 'pfb' is taken to
384 mean a t1 postscript font. If Imager cannot tell which type a font is
385 you can tell it explicitly by using the C<type> parameter:
387 $t1font = Imager::Font->new(file => 'fruitcase', type => 't1');
388 $ttfont = Imager::Font->new(file => 'arglebarf', type => 'tt');
390 The C<index> parameter is used to select a single face from a font
391 file containing more than one face, for example, from a Macintosh font
392 suitcase or a .dfont file.
394 If any of the C<color>, C<size> or C<aa> parameters are omitted when
395 calling C<Imager::Font->new()> the they take the following values:
397 color => Imager::Color->new(255, 0, 0, 0); # this default should be changed
402 To use Win32 fonts supply the facename of the font:
404 $font = Imager::Font->new(face=>'Arial Bold Italic');
406 There isn't any access to other logical font attributes, but this
407 typically isn't necessary for Win32 TrueType fonts, since you can
408 contruct the full name of the font as above.
410 Other logical font attributes may be added if there is sufficient demand.
414 Returns the bounding box for the specified string. Example:
423 $right_bearing) = $font->bounding_box(string => "A Fool");
425 my $bbox_object = $font->bounding_box(string => "A Fool");
431 the relative start of a the string. In some
432 cases this can be a negative number, in that case the first letter
433 stretches to the left of the starting position that is specified in
434 the string method of the Imager class
436 =item C<$global_descent>
438 how far down the lowest letter of the entire font reaches below the
439 baseline (this is often j).
443 how wide the string from
444 the starting position is. The total width of the string is
445 C<$pos_width-$neg_width>.
451 the same as <$global_descent> and <$global_ascent> except that they
452 are only for the characters that appear in the string.
454 =item C<$advance_width>
456 the distance from the start point that the next string output should
457 start at, this is often the same as C<$pos_width>, but can be
458 different if the final character overlaps the right side of its
461 =item C<$right_bearing>
463 The distance from the right side of the final glyph to the end of the
464 advance width. If the final glyph overflows the advance width this
469 Obviously we can stuff all the results into an array just as well:
471 @metrics = $font->bounding_box(string => "testing 123");
473 Note that extra values may be added, so $metrics[-1] isn't supported.
474 It's possible to translate the output by a passing coordinate to the
477 @metrics = $font->bounding_box(string => "testing 123", x=>45, y=>34);
479 This gives the bounding box as if the string had been put down at C<(x,y)>
480 By giving bounding_box 'canon' as a true value it's possible to measure
481 the space needed for the string:
483 @metrics = $font->bounding_box(string=>"testing",size=>15,canon=>1);
485 This returns tha same values in $metrics[0] and $metrics[1],
488 $bbox[2] - horizontal space taken by glyphs
489 $bbox[3] - vertical space taken by glyphs
491 Returns an L<Imager::Font::BBox> object in scalar context, so you can
492 avoid all those confusing indices. This has methods as named above,
493 with some extra convenience methods.
497 This is a method of the Imager class but because it's described in
498 here since it belongs to the font routines. Example:
501 $img->read(file=>"test.jpg");
502 $img->string(font=>$t1font,
508 $img->write(file=>"testout.jpg");
510 This would put a 40 pixel high text in the top left corner of an
511 image. If you measure the actuall pixels it varies since the fonts
512 usually do not use their full height. It seems that the color and
513 size can be specified twice. When a font is created only the actual
514 font specified matters. It his however convenient to store default
515 values in a font, such as color and size. If parameters are passed to
516 the string function they are used instead of the defaults stored in
519 The following parameters can be supplied to the string() method:
525 The text to be rendered. If this isn't present the 'text' parameter
526 is used. If neither is present the call will fail.
530 If non-zero the output will be anti-aliased.
536 The start point for rendering the text. See the align parameter.
540 If non-zero the point supplied in (x,y) will be on the base-line, if
541 zero then (x,y) will be at the top-left of the string.
543 ie. if drawing the string "yA" and align is 0 the point (x,y) will
544 aligned with the top of the A. If align is 1 (the default) it will be
545 aligned with the baseline of the font, typically bottom of the A,
546 depending on the font used.
550 If present, the text will be written to the specified channel of the
551 image and the color parameter will be ignore.
555 The color to draw the text in.
559 The point-size to draw the text at.
563 For drivers that support it, the width to draw the text at. Defaults
564 to be value of the 'size' parameter.
568 For drivers that support it, treat the string as UTF8 encoded. For
569 versions of perl that support Unicode (5.6 and later), this will be
570 enabled automatically if the 'string' parameter is already a UTF8
571 string. See L<UTF8> for more information.
575 For drivers that support it, draw the text vertically. Note: I
576 haven't found a font that has the appropriate metrics yet.
580 If string() is called with the C<channel> parameter then the color
581 isn't used and the font is drawn in only one channel of the image.
582 This can be quite handy to create overlays. See the examples for tips
585 Sometimes it is necessary to know how much space a string takes before
586 rendering it. The bounding_box() method described earlier can be used
589 =item align(string=>$text, size=>$size, x=>..., y=>..., valign => ..., halign=>...)
591 Higher level text output - outputs the text aligned as specified
592 around the given point (x,y).
594 # "Hello" centered at 100, 100 in the image.
595 my ($left, $top, $bottom, $right) =
596 $font->align(string=>"Hello",
598 halign=>'center', valign=>'center',
601 Takes the same parameters as $font->draw(), and the following extra
614 Point is at the top of the text.
618 Point is at the bottom of the text.
622 Point is on the baseline of the text (default.)
626 Point is vertically centered within the text.
636 The point is at the left of the text.
640 The point is at the start point of the text.
644 The point is horizontally centered within the text.
648 The point is at the right end of the text.
652 The point is at the right end of the text. This will change to the
653 end point of the text (once the proper bounding box interfaces are
660 The image to draw to. Set to C<undef> to avoid drawing but still
661 calculate the bounding box.
665 Returns a list specifying the bounds of the drawn text.
669 =item dpi(xdpi=>$xdpi, ydpi=>$ydpi)
673 Set retrieve the spatial resolution of the image in dots per inch.
674 The default is 72 dpi.
676 This isn't implemented for all font types yet.
678 =item transform(matrix=>$matrix)
680 Applies a transformation to the font, where matrix is an array ref of
681 numbers representing a 2 x 3 matrix:
683 [ $matrix->[0], $matrix->[1], $matrix->[2],
684 $matrix->[3], $matrix->[4], $matrix->[5] ]
686 Not all font types support transformations, these will return false.
688 It's possible that a driver will disable hinting if you use a
689 transformation, to prevent discontinuities in the transformations.
690 See the end of the test script t/t38ft2font.t for an example.
692 Currently only the ft2 (Freetype 2.x) driver supports the transform()
695 =item has_chars(string=>$text)
697 Checks if the characters in $text are defined by the font.
699 In a list context returns a list of true or false value corresponding
700 to the characters in $text, true if the character is defined, false if
701 not. In scalar context returns a string of NUL or non-NUL
702 characters. Supports UTF8 where the font driver supports UTF8.
704 Not all fonts support this method (use $font->can("has_chars") to
709 This method doesn't exist yet but is under consideration. It would mostly
710 be helpful for generating small tests and such. Its proposed interface is:
712 $img = $font->logo(string=>"Plan XYZ", color=>$blue, border=>7);
714 This would be nice for writing (admittedly multiline) one liners like:
716 Imager::Font->new(file=>"arial.ttf", color=>$blue, aa=>1)
717 ->string(text=>"Plan XYZ", border=>5)
718 ->write(file=>"xyz.png");
722 Returns the internal name of the face. Not all font types support
725 =item glyph_names(string=>$string [, utf8=>$utf8 ][, reliable_only=>0 ] );
727 Returns a list of glyph names for each of the characters in the
728 string. If the character has no name then C<undef> is returned for
731 Some font files do not include glyph names, in this case Freetype 2
732 will not return any names. Freetype 1 can return standard names even
733 if there are no glyph names in the font.
735 Freetype 2 has an API function that returns true only if the font has
736 "reliable glyph names", unfortunately this always returns false for
737 TTF fonts. This can avoid the check of this API by supplying
738 C<reliable_only> as 0. The consequences of using this on an unknown
739 font may be unpredictable, since the Freetype documentation doesn't
740 say how those name tables are unreliable, or how FT2 handles them.
742 Both Freetype 1.x and 2.x allow support for glyph names to not be
747 =head1 MULTIPLE MASTER FONTS
749 The Freetype 2 driver supports multiple master fonts:
755 Test if the font is a multiple master font.
759 Returns a list of the axes that can be changes in the font. Each
760 entry is an array reference which contains:
770 minimum value for this axis.
774 maximum value for this axis
778 =item set_mm_coords(coords=>\@values)
780 Blends an interpolated design from the master fonts. @values must
781 contain as many values as there are axes in the font.
785 For example, to select the minimum value in each axis:
787 my @axes = $font->mm_axes;
788 my @coords = map $_->[1], @axes;
789 $font->set_mm_coords(coords=>\@coords);
791 It's possible other drivers will support multiple master fonts in the
792 future, check if your selected font object supports the is_mm() method
793 using the can() method.
797 There are 2 ways of rendering Unicode characters with Imager:
803 For versions of perl that support it, use perl's native UTF8 strings.
804 This is the simplest method.
808 Hand build your own UTF8 encoded strings. Only recommended if your
809 version of perl has no UTF8 support.
813 Imager won't construct characters for you, so if want to output
814 unicode character 00C3 "LATIN CAPITAL LETTER A WITH DIAERESIS", and
815 your font doesn't support it, Imager will I<not> build it from 0041
816 "LATIN CAPITAL LETTER A" and 0308 "COMBINING DIAERESIS".
818 =head2 Native UTF8 Support
820 If your version of perl supports UTF8 and the driver supports UTF8,
821 just use the $im->string() method, and it should do the right thing.
823 =head2 Build your own
825 In this case you need to build your own UTF8 encoded characters.
829 $x = pack("C*", 0xE2, 0x80, 0x90); # character code 0x2010 HYPHEN
831 You need to be be careful with versions of perl that have UTF8
832 support, since your string may end up doubly UTF8 encoded.
836 $x = "A\xE2\x80\x90\x41\x{2010}";
837 substr($x, -1, 0) = "";
838 # at this point $x is has the UTF8 flag set, but has 5 characters,
839 # none, of which is the constructed UTF8 character
841 The test script t/t38ft2font.t has a small example of this after the
844 # an attempt using emulation of UTF8
846 =head1 DRIVER CONTROL
848 If you don't supply a 'type' parameter to Imager::Font->new(), but you
849 do supply a 'file' parameter, Imager will attempt to guess which font
850 driver to used based on the extension of the font file.
852 Since some formats can be handled by more than one driver, a priority
853 list is used to choose which one should be used, if a given format can
854 be handled by more than one driver.
856 The current priority can be retrieved with:
858 @drivers = Imager::Font->priorities();
860 You can set new priorities and save the old priorities with:
862 @old = Imager::Font->priorities(@drivers);
864 If you supply driver names that are not currently supported, they will
867 Imager supports both T1Lib and Freetype2 for working with Type 1
868 fonts, but currently only T1Lib does any caching, so by default T1Lib
869 is given a higher priority. Since Imager's Freetype2 support can also
870 do font transformations, you may want to give that a higher priority:
872 my @old = Imager::Font->priorities(qw(tt ft2 t1));
876 Arnar M. Hrafnkelsson, addi@umich.edu
877 And a great deal of help from others - see the README for a complete
882 You need to modify this class to add new font types.
884 The $pos_width member returned by the bounding_box() method has
885 historically returned different values from different drivers. The
886 Freetype 1.x and 2.x, and the Win32 drivers return the max of the
887 advance width and the right edge of the right-most glyph. The Type 1
888 driver always returns the right edge of the right-most glyph.
890 The newer advance_width and right_bearing values allow access to any
895 Imager(3), Imager::Font::FreeType2(3), Imager::Font::Type1(3),
896 Imager::Font::Win32(3), Imager::Font::Truetype(3), Imager::Font::BBox(3)
898 http://imager.perl.org/