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 my $image = $input{image};
127 $input{string} = _first($input{string}, $input{text});
128 unless (defined $input{string}) {
129 $image->_set_error("Missing required parameter 'string'");
132 $input{aa} = _first($input{aa}, $input{antialias}, $self->{aa}, 1);
133 # the original draw code worked this out but didn't use it
134 $input{align} = _first($input{align}, $self->{align});
135 $input{color} = _first($input{color}, $self->{color});
136 $input{color} = Imager::_color($input{'color'});
138 $input{size} = _first($input{size}, $self->{size});
139 unless (defined $input{size}) {
140 $image->_set_error("No font size provided");
143 $input{align} = _first($input{align}, 1);
144 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
145 $input{vlayout} = _first($input{vlayout}, $self->{vlayout}, 0);
147 my $result = $self->_draw(%input);
149 $image->_set_error($image->_error_as_msg());
157 my %input = ( halign => 'left', valign => 'baseline',
158 'x' => 0, 'y' => 0, @_ );
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'");
166 my $errors_to = $input{image} || 'Imager';
168 my $text = _first($input{string}, $input{text});
169 unless (defined $text) {
170 $errors_to->_set_error("Missing required parameter 'string'");
174 my $size = _first($input{size}, $self->{size});
175 my $utf8 = _first($input{utf8}, 0);
177 my $bbox = $self->bounding_box(string=>$text, size=>$size, utf8=>$utf8);
178 my $valign = $input{valign};
180 unless $valign && $valign =~ /^(?:top|center|bottom|baseline)$/;
182 my $halign = $input{halign};
184 unless $halign && $halign =~ /^(?:left|start|center|end|right)$/;
189 if ($valign eq 'top') {
192 elsif ($valign eq 'center') {
193 $y += $bbox->ascent - $bbox->text_height / 2;
195 elsif ($valign eq 'bottom') {
196 $y += $bbox->descent;
198 # else baseline is the default
200 if ($halign eq 'left') {
201 $x -= $bbox->start_offset;
203 elsif ($halign eq 'start') {
206 elsif ($halign eq 'center') {
207 $x -= $bbox->start_offset + $bbox->total_width / 2;
209 elsif ($halign eq 'end') {
210 $x -= $bbox->advance_width;
212 elsif ($halign eq 'right') {
213 $x -= $bbox->advance_width - $bbox->right_bearing;
219 delete @input{qw/x y/};
220 $self->draw(%input, 'x' => $x, 'y' => $y, align=>1)
224 return ($x+$bbox->start_offset, $y-$bbox->ascent,
225 $x+$bbox->end_offset, $y-$bbox->descent+1);
232 if (!exists $input{'string'}) {
233 $Imager::ERRSTR='string parameter missing';
236 $input{size} ||= $self->{size};
237 $input{sizew} = _first($input{sizew}, $self->{sizew}, 0);
238 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
240 my @box = $self->_bounding_box(%input);
243 if(@box && exists $input{'x'} and exists $input{'y'}) {
244 my($gdescent, $gascent)=@box[1,3];
245 $box[1]=$input{'y'}-$gascent; # top = base - ascent (Y is down)
246 $box[3]=$input{'y'}-$gdescent; # bottom = base - descent (Y is down, descent is negative)
247 $box[0]+=$input{'x'};
248 $box[2]+=$input{'x'};
249 } elsif (@box && $input{'canon'}) {
250 $box[3]-=$box[1]; # make it cannoical (ie (0,0) - (width, height))
256 require Imager::Font::BBox;
258 return Imager::Font::BBox->new(@box);
265 # I'm assuming a default of 72 dpi
268 $Imager::ERRSTR = "Setting dpi not implemented for this font type";
280 # this is split into transform() and _transform() so we can
281 # implement other tags like: degrees=>12, which would build a
282 # 12 degree rotation matrix
283 # but I'll do that later
284 unless ($hsh{matrix}) {
285 $Imager::ERRSTR = "You need to supply a matrix";
289 return $self->_transform(%hsh);
293 $Imager::ERRSTR = "This type of font cannot be transformed";
306 @priority = grep Imager::i_has_format($_), @_;
317 Imager::Font - Font handling for Imager.
321 $t1font = Imager::Font->new(file => 'pathtofont.pfb');
322 $ttfont = Imager::Font->new(file => 'pathtofont.ttf');
323 $w32font = Imager::Font->new(face => 'Times New Roman');
325 $blue = Imager::Color->new("#0000FF");
326 $font = Imager::Font->new(file => 'pathtofont.ttf',
337 $right_bearing) = $font->bounding_box(string=>"Foo");
339 my $bbox_object = $font->bounding_box(string=>"Foo");
341 # documented in Imager::Draw
342 $img->string(font => $font,
352 This module handles creating Font objects used by imager. The module
353 also handles querying fonts for sizes and such. If both T1lib and
354 freetype were avaliable at the time of compilation then Imager should
355 be able to work with both truetype fonts and t1 postscript fonts. To
356 check if Imager is t1 or truetype capable you can use something like
360 print "Has truetype" if $Imager::formats{tt};
361 print "Has t1 postscript" if $Imager::formats{t1};
362 print "Has Win32 fonts" if $Imager::formats{w32};
363 print "Has Freetype2" if $Imager::formats{ft2};
369 This creates a font object to pass to functions that take a font argument.
371 $font = Imager::Font->new(file => 'denmark.ttf',
377 This creates a font which is the truetype font denmark.ttf. It's
378 default color is $blue, default size is 30 pixels and it's rendered
379 antialised by default. Imager can see which type of font a file is by
380 looking at the suffix of the filename for the font. A suffix of 'ttf'
381 is taken to mean a truetype font while a suffix of 'pfb' is taken to
382 mean a t1 postscript font. If Imager cannot tell which type a font is
383 you can tell it explicitly by using the C<type> parameter:
385 $t1font = Imager::Font->new(file => 'fruitcase', type => 't1');
386 $ttfont = Imager::Font->new(file => 'arglebarf', type => 'tt');
388 The C<index> parameter is used to select a single face from a font
389 file containing more than one face, for example, from a Macintosh font
390 suitcase or a .dfont file.
392 If any of the C<color>, C<size> or C<aa> parameters are omitted when
393 calling C<Imager::Font->new()> the they take the following values:
395 color => Imager::Color->new(255, 0, 0, 0); # this default should be changed
400 To use Win32 fonts supply the facename of the font:
402 $font = Imager::Font->new(face=>'Arial Bold Italic');
404 There isn't any access to other logical font attributes, but this
405 typically isn't necessary for Win32 TrueType fonts, since you can
406 contruct the full name of the font as above.
408 Other logical font attributes may be added if there is sufficient demand.
416 file - name of the file to load the font from.
420 face - face name. This is used only under Win32 to create a GDI based
421 font. This is ignored if the C<file> parameter is supplied.
425 type - font driver to use. Currently the permitted values for this are:
431 tt - Freetype 1.x driver. Supports TTF fonts.
435 t1 - T1 Lib driver. Supports Postscript Type 1 fonts. Allows for
436 synthesis of underline, strikethrough and overline.
440 ft2 - Freetype 2.x driver. Supports many different font formats.
441 Also supports the transform() method.
447 color - the default color used with this font. Default: red.
451 size - the default size used with this font. Default: 15.
455 utf8 - if non-zero then text supplied to $img->string(...) and
456 $font->bounding_box(...) is assumed to be UTF 8 encoded by default.
460 align - the default value for the $img->string(...) C<align>
461 parameter. Default: 1.
465 vlayout - the default value for the $img->string(...) C<vlayout>
466 parameter. Default: 0.
470 aa - the default value for the $im->string(...) C<aa> parameter.
475 index - for font file containing multiple fonts this selects which
476 font to use. This is useful for Macintosh DFON (.dfont) and suitcase
479 If you want to use a suitcase font you will need to tell Imager to use
480 the FreeType 2.x driver by setting C<type> to C<'ft2'>:
482 my $font = Imager::Font->new(file=>$file, index => 1, type=>'ft2')
483 or die Imager->errstr;
491 Returns the bounding box for the specified string. Example:
500 $right_bearing) = $font->bounding_box(string => "A Fool");
502 my $bbox_object = $font->bounding_box(string => "A Fool");
508 the relative start of a the string. In some
509 cases this can be a negative number, in that case the first letter
510 stretches to the left of the starting position that is specified in
511 the string method of the Imager class
513 =item C<$global_descent>
515 how far down the lowest letter of the entire font reaches below the
516 baseline (this is often j).
520 how wide the string from
521 the starting position is. The total width of the string is
522 C<$pos_width-$neg_width>.
528 the same as <$global_descent> and <$global_ascent> except that they
529 are only for the characters that appear in the string.
531 =item C<$advance_width>
533 the distance from the start point that the next string output should
534 start at, this is often the same as C<$pos_width>, but can be
535 different if the final character overlaps the right side of its
538 =item C<$right_bearing>
540 The distance from the right side of the final glyph to the end of the
541 advance width. If the final glyph overflows the advance width this
546 Obviously we can stuff all the results into an array just as well:
548 @metrics = $font->bounding_box(string => "testing 123");
550 Note that extra values may be added, so $metrics[-1] isn't supported.
551 It's possible to translate the output by a passing coordinate to the
554 @metrics = $font->bounding_box(string => "testing 123", x=>45, y=>34);
556 This gives the bounding box as if the string had been put down at C<(x,y)>
557 By giving bounding_box 'canon' as a true value it's possible to measure
558 the space needed for the string:
560 @metrics = $font->bounding_box(string=>"testing",size=>15,canon=>1);
562 This returns tha same values in $metrics[0] and $metrics[1],
565 $bbox[2] - horizontal space taken by glyphs
566 $bbox[3] - vertical space taken by glyphs
568 Returns an L<Imager::Font::BBox> object in scalar context, so you can
569 avoid all those confusing indices. This has methods as named above,
570 with some extra convenience methods.
578 string - the string to calculate the bounding box for. Required.
582 size - the font size to use. Default: value set in
583 Imager::Font->new(), or 15.
587 sizew - the font width to use. Default to the value of the C<size>
592 utf8 - For drivers that support it, treat the string as UTF8 encoded.
593 For versions of perl that support Unicode (5.6 and later), this will
594 be enabled automatically if the 'string' parameter is already a UTF8
595 string. See L<UTF8> for more information. Default: the C<utf8> value
596 passed to Imager::Font->new(...) or 0.
600 x, y - offsets applied to @box[0..3] to give you a adjusted bounding
601 box. Ignored in scalar context.
605 canon - if non-zero and the C<x>, C<y> parameters are not supplied,
606 then $pos_width and $global_ascent values will returned as the width
607 and height of the text instead.
613 The $img->string(...) method is now documented in
614 L<Imager::Draw/string>
616 =item align(string=>$text, size=>$size, x=>..., y=>..., valign => ..., halign=>...)
618 Higher level text output - outputs the text aligned as specified
619 around the given point (x,y).
621 # "Hello" centered at 100, 100 in the image.
622 my ($left, $top, $right, $bottom) =
623 $font->align(string=>"Hello",
625 halign=>'center', valign=>'center',
628 Takes the same parameters as $font->draw(), and the following extra
641 Point is at the top of the text.
645 Point is at the bottom of the text.
649 Point is on the baseline of the text (default.)
653 Point is vertically centered within the text.
663 The point is at the left of the text.
667 The point is at the start point of the text.
671 The point is horizontally centered within the text.
675 The point is at the right end of the text.
679 The point is at the end point of the text.
685 The image to draw to. Set to C<undef> to avoid drawing but still
686 calculate the bounding box.
690 Returns a list specifying the bounds of the drawn text.
694 =item dpi(xdpi=>$xdpi, ydpi=>$ydpi)
698 Set or retrieve the spatial resolution of the image in dots per inch.
699 The default is 72 dpi.
701 This isn't implemented for all font types yet.
703 Possible parameters are:
709 xdpi, ydpi - set the horizontal and vertical resolution in dots per
714 dpi - set both horizontal and vertical resolution to this value.
718 Returns a list containing the previous xdpi, ydpi values.
720 =item transform(matrix=>$matrix)
722 Applies a transformation to the font, where matrix is an array ref of
723 numbers representing a 2 x 3 matrix:
725 [ $matrix->[0], $matrix->[1], $matrix->[2],
726 $matrix->[3], $matrix->[4], $matrix->[5] ]
728 Not all font types support transformations, these will return false.
730 It's possible that a driver will disable hinting if you use a
731 transformation, to prevent discontinuities in the transformations.
732 See the end of the test script t/t38ft2font.t for an example.
734 Currently only the ft2 (Freetype 2.x) driver supports the transform()
737 See samples/slant_text.pl for a sample using this function.
739 Note that the transformation is done in font co-ordinates where y
740 increases as you move up, not image co-ordinates where y decreases as
743 =item has_chars(string=>$text)
745 Checks if the characters in $text are defined by the font.
747 In a list context returns a list of true or false value corresponding
748 to the characters in $text, true if the character is defined, false if
749 not. In scalar context returns a string of NUL or non-NUL
750 characters. Supports UTF8 where the font driver supports UTF8.
752 Not all fonts support this method (use $font->can("has_chars") to
759 string - string of characters to check for. Required. Must contain
760 at least one character.
764 utf8 - For drivers that support it, treat the string as UTF8 encoded.
765 For versions of perl that support Unicode (5.6 and later), this will
766 be enabled automatically if the 'string' parameter is already a UTF8
767 string. See L<UTF8> for more information. Default: the C<utf8> value
768 passed to Imager::Font->new(...) or 0.
774 Returns the internal name of the face. Not all font types support
777 =item glyph_names(string=>$string [, utf8=>$utf8 ][, reliable_only=>0 ] );
779 Returns a list of glyph names for each of the characters in the
780 string. If the character has no name then C<undef> is returned for
783 Some font files do not include glyph names, in this case Freetype 2
784 will not return any names. Freetype 1 can return standard names even
785 if there are no glyph names in the font.
787 Freetype 2 has an API function that returns true only if the font has
788 "reliable glyph names", unfortunately this always returns false for
789 TTF fonts. This can avoid the check of this API by supplying
790 C<reliable_only> as 0. The consequences of using this on an unknown
791 font may be unpredictable, since the Freetype documentation doesn't
792 say how those name tables are unreliable, or how FT2 handles them.
794 Both Freetype 1.x and 2.x allow support for glyph names to not be
799 This is used by Imager's string() method to implement drawing text.
800 See L<Imager::Draw/string>.
804 =head1 MULTIPLE MASTER FONTS
806 The Freetype 2 driver supports multiple master fonts:
812 Test if the font is a multiple master font.
816 Returns a list of the axes that can be changes in the font. Each
817 entry is an array reference which contains:
827 minimum value for this axis.
831 maximum value for this axis
835 =item set_mm_coords(coords=>\@values)
837 Blends an interpolated design from the master fonts. @values must
838 contain as many values as there are axes in the font.
842 For example, to select the minimum value in each axis:
844 my @axes = $font->mm_axes;
845 my @coords = map $_->[1], @axes;
846 $font->set_mm_coords(coords=>\@coords);
848 It's possible other drivers will support multiple master fonts in the
849 future, check if your selected font object supports the is_mm() method
850 using the can() method.
854 There are 2 ways of rendering Unicode characters with Imager:
860 For versions of perl that support it, use perl's native UTF8 strings.
861 This is the simplest method.
865 Hand build your own UTF8 encoded strings. Only recommended if your
866 version of perl has no UTF8 support.
870 Imager won't construct characters for you, so if want to output
871 unicode character 00C3 "LATIN CAPITAL LETTER A WITH DIAERESIS", and
872 your font doesn't support it, Imager will I<not> build it from 0041
873 "LATIN CAPITAL LETTER A" and 0308 "COMBINING DIAERESIS".
875 To check if a driver supports UTF8 call the utf8 method:
881 Return true if the font supports UTF8.
885 =head2 Native UTF8 Support
887 If your version of perl supports UTF8 and the driver supports UTF8,
888 just use the $im->string() method, and it should do the right thing.
890 =head2 Build your own
892 In this case you need to build your own UTF8 encoded characters.
896 $x = pack("C*", 0xE2, 0x80, 0x90); # character code 0x2010 HYPHEN
898 You need to be be careful with versions of perl that have UTF8
899 support, since your string may end up doubly UTF8 encoded.
903 $x = "A\xE2\x80\x90\x41\x{2010}";
904 substr($x, -1, 0) = "";
905 # at this point $x is has the UTF8 flag set, but has 5 characters,
906 # none, of which is the constructed UTF8 character
908 The test script t/t38ft2font.t has a small example of this after the
911 # an attempt using emulation of UTF8
913 =head1 DRIVER CONTROL
915 If you don't supply a 'type' parameter to Imager::Font->new(), but you
916 do supply a 'file' parameter, Imager will attempt to guess which font
917 driver to used based on the extension of the font file.
919 Since some formats can be handled by more than one driver, a priority
920 list is used to choose which one should be used, if a given format can
921 be handled by more than one driver.
927 The current priorities can be retrieved with:
929 @drivers = Imager::Font->priorities();
931 You can set new priorities and save the old priorities with:
933 @old = Imager::Font->priorities(@drivers);
937 If you supply driver names that are not currently supported, they will
940 Imager supports both T1Lib and Freetype2 for working with Type 1
941 fonts, but currently only T1Lib does any caching, so by default T1Lib
942 is given a higher priority. Since Imager's Freetype2 support can also
943 do font transformations, you may want to give that a higher priority:
945 my @old = Imager::Font->priorities(qw(tt ft2 t1));
949 Arnar M. Hrafnkelsson, addi@umich.edu
950 And a great deal of help from others - see the README for a complete
955 You need to modify this class to add new font types.
957 The $pos_width member returned by the bounding_box() method has
958 historically returned different values from different drivers. The
959 Freetype 1.x and 2.x, and the Win32 drivers return the max of the
960 advance width and the right edge of the right-most glyph. The Type 1
961 driver always returns the right edge of the right-most glyph.
963 The newer advance_width and right_bearing values allow access to any
972 Imager(3), Imager::Font::FreeType2(3), Imager::Font::Type1(3),
973 Imager::Font::Win32(3), Imager::Font::Truetype(3), Imager::Font::BBox(3)
975 http://imager.perl.org/