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',
20 description => 'FreeType 1.x',
24 class=>'Imager::Font::T1',
25 module=>'Imager/Font/T1.pm',
27 description => 'T1Lib',
30 class=>'Imager::Font::FT2',
31 module=>'Imager/Font/FT2.pm',
32 files=>'.*\.(pfa|pfb|otf|ttf|fon|fnt|dfont|pcf(\.gz)?)$',
33 description => 'FreeType 2.x',
36 class=>'Imager::Font::Image',
37 module=>'Imager/Font/Image.pm',
41 class=>'Imager::Font::W32',
42 module=>'Imager/Font/W32.pm',
43 description => 'Win32 GDI Fonts',
47 # this currently should only contain file based types, don't add w32
48 my @priority = qw(t1 tt ft2 ifs);
53 my ($file, $type, $id);
54 my %hsh=(color => Imager::Color->new(255,0,0,255),
65 unless ($drivers{$type}) {
66 Imager->_set_error("Unknown font type $type");
70 unless ($Imager::formats{$type}) {
71 Imager->_set_error("The $type {$drivers{$type}) font driver is not installed");
76 for my $drv (@priority) {
78 my $re = $drivers{$drv}{files} or next;
79 if ($file =~ /$re/i) {
80 if (eval { require $drivers{$drv}{module}; 1 } and !( $drivers{$drv}{checktype} && !$Imager::formats{$drv} )) {
87 if (!defined($type)) {
88 # some types we can support, but the driver isn't available
89 # work out which drivers support it, so we can provide the user
90 # some useful information on how to get it working
92 for my $driver_name (keys %drivers) {
93 my $driver = $drivers{$driver_name};
94 push @not_here, "$driver_name ($driver->{description})"
95 if $driver->{files} && $file =~ /$driver->{files}/i;
98 $Imager::ERRSTR = "No font drivers enabled that can support this file, rebuild Imager with any of ".join(", ", @not_here)." to use this font file";
101 $Imager::ERRSTR = "No font type found for $hsh{'file'}";
105 } elsif ($hsh{face}) {
108 $Imager::ERRSTR="No font file specified";
112 if ($drivers{$type}{checktype} && !$Imager::formats{$type}) {
113 $Imager::ERRSTR = "`$type' not enabled";
117 # here we should have the font type or be dead already.
119 require $drivers{$type}{module};
120 return $drivers{$type}{class}->new(%hsh);
123 # returns first defined parameter
126 return $_ if defined $_;
133 my %input = ('x' => 0, 'y' => 0, @_);
134 unless ($input{image}) {
135 $Imager::ERRSTR = 'No image supplied to $font->draw()';
138 my $image = $input{image};
139 $input{string} = _first($input{string}, $input{text});
140 unless (defined $input{string}) {
141 $image->_set_error("Missing required parameter 'string'");
144 $input{aa} = _first($input{aa}, $input{antialias}, $self->{aa}, 1);
145 # the original draw code worked this out but didn't use it
146 $input{align} = _first($input{align}, $self->{align});
147 $input{color} = _first($input{color}, $self->{color});
148 $input{color} = Imager::_color($input{'color'});
150 $input{size} = _first($input{size}, $self->{size});
151 unless (defined $input{size}) {
152 $image->_set_error("No font size provided");
155 $input{align} = _first($input{align}, 1);
156 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
157 $input{vlayout} = _first($input{vlayout}, $self->{vlayout}, 0);
159 my $result = $self->_draw(%input);
161 $image->_set_error($image->_error_as_msg());
169 my %input = ( halign => 'left', valign => 'baseline',
170 'x' => 0, 'y' => 0, @_ );
172 # image needs to be supplied, but can be supplied as undef
173 unless (exists $input{image}) {
174 Imager->_set_error("Missing required parameter 'image'");
178 my $errors_to = $input{image} || 'Imager';
180 my $text = _first($input{string}, $input{text});
181 unless (defined $text) {
182 $errors_to->_set_error("Missing required parameter 'string'");
186 my $size = _first($input{size}, $self->{size});
187 my $utf8 = _first($input{utf8}, 0);
189 my $bbox = $self->bounding_box(string=>$text, size=>$size, utf8=>$utf8);
190 my $valign = $input{valign};
192 unless $valign && $valign =~ /^(?:top|center|bottom|baseline)$/;
194 my $halign = $input{halign};
196 unless $halign && $halign =~ /^(?:left|start|center|end|right)$/;
201 if ($valign eq 'top') {
204 elsif ($valign eq 'center') {
205 $y += $bbox->ascent - $bbox->text_height / 2;
207 elsif ($valign eq 'bottom') {
208 $y += $bbox->descent;
210 # else baseline is the default
212 if ($halign eq 'left') {
213 $x -= $bbox->start_offset;
215 elsif ($halign eq 'start') {
218 elsif ($halign eq 'center') {
219 $x -= $bbox->start_offset + $bbox->total_width / 2;
221 elsif ($halign eq 'end') {
222 $x -= $bbox->advance_width;
224 elsif ($halign eq 'right') {
225 $x -= $bbox->advance_width - $bbox->right_bearing;
231 delete @input{qw/x y/};
232 $self->draw(%input, 'x' => $x, 'y' => $y, align=>1)
236 return ($x+$bbox->start_offset, $y-$bbox->ascent,
237 $x+$bbox->end_offset, $y-$bbox->descent+1);
244 if (!exists $input{'string'}) {
245 $Imager::ERRSTR='string parameter missing';
248 $input{size} ||= $self->{size};
249 $input{sizew} = _first($input{sizew}, $self->{sizew}, 0);
250 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
252 my @box = $self->_bounding_box(%input)
256 if(@box && exists $input{'x'} and exists $input{'y'}) {
257 my($gdescent, $gascent)=@box[1,3];
258 $box[1]=$input{'y'}-$gascent; # top = base - ascent (Y is down)
259 $box[3]=$input{'y'}-$gdescent; # bottom = base - descent (Y is down, descent is negative)
260 $box[0]+=$input{'x'};
261 $box[2]+=$input{'x'};
262 } elsif (@box && $input{'canon'}) {
263 $box[3]-=$box[1]; # make it canonical (ie (0,0) - (width, height))
269 require Imager::Font::BBox;
271 return Imager::Font::BBox->new(@box);
278 # I'm assuming a default of 72 dpi
281 $Imager::ERRSTR = "Setting dpi not implemented for this font type";
293 # this is split into transform() and _transform() so we can
294 # implement other tags like: degrees=>12, which would build a
295 # 12 degree rotation matrix
296 # but I'll do that later
297 unless ($hsh{matrix}) {
298 $Imager::ERRSTR = "You need to supply a matrix";
302 return $self->_transform(%hsh);
306 $Imager::ERRSTR = "This type of font cannot be transformed";
325 my ($self, %opts) = @_;
327 my $type = delete $opts{type};
328 my $class = delete $opts{class};
329 my $files = delete $opts{files};
330 my $description = delete $opts{description} || $class;
333 or return Imager->_set_error("No type parameter supplied to Imager::Font->regster");
336 or return Imager->_set_error("No class parameter supplied to Imager::Font->register");
340 or return Imager->_set_error("files isn't a valid regexp");
343 if ($drivers{$type} && $drivers{$type}{class} ne $class) {
344 Imager->_set_error("Font type $type already registered as $drivers{$type}{class}");
348 (my $module = $class . ".pm") =~ s(::)(/)g;
354 description => $description,
356 $files and $driver->{files} = $files;
358 $drivers{$type} = $driver;
369 Imager::Font - Font handling for Imager.
375 $t1font = Imager::Font->new(file => 'pathtofont.pfb');
376 $ttfont = Imager::Font->new(file => 'pathtofont.ttf');
377 $w32font = Imager::Font->new(face => 'Times New Roman');
379 $blue = Imager::Color->new("#0000FF");
380 $font = Imager::Font->new(file => 'pathtofont.ttf',
391 $right_bearing) = $font->bounding_box(string=>"Foo");
393 my $bbox_object = $font->bounding_box(string=>"Foo");
395 # documented in Imager::Draw
396 $img->string(font => $font,
406 =for stopwords TrueType FreeType
408 This module handles creating Font objects used by Imager. The module
409 also handles querying fonts for sizes and such. If both T1lib and
410 FreeType were available at the time of compilation then Imager should
411 be able to work with both TrueType fonts and t1 Postscript fonts. To
412 check if Imager is t1 or TrueType capable you can use something like
416 print "Has truetype" if $Imager::formats{tt};
417 print "Has t1 postscript" if $Imager::formats{t1};
418 print "Has Win32 fonts" if $Imager::formats{w32};
419 print "Has Freetype2" if $Imager::formats{ft2};
425 This creates a font object to pass to functions that take a font argument.
427 $font = Imager::Font->new(file => 'denmark.ttf',
433 This creates a font which is the TrueType font F<denmark.ttf>. It's
434 default color is $blue, default size is 30 pixels and it's rendered
435 anti-aliased by default. Imager can see which type of font a file is
436 by looking at the suffix of the file name for the font. A suffix of
437 C<ttf> is taken to mean a TrueType font while a suffix of C<pfb> is
438 taken to mean a Type 1 Postscript font. If Imager cannot tell which
439 type a font is you can tell it explicitly by using the C<type>
442 $t1font = Imager::Font->new(file => 'fruitcase', type => 't1');
443 $ttfont = Imager::Font->new(file => 'arglebarf', type => 'tt');
445 The C<index> parameter is used to select a single face from a font
446 file containing more than one face, for example, from a Macintosh font
447 suitcase or a C<.dfont> file.
449 If any of the C<color>, C<size> or C<aa> parameters are omitted when
450 calling C<< Imager::Font->new() >> the they take the following values:
452 color => Imager::Color->new(255, 0, 0, 0); # this default should be changed
457 To use Win32 fonts supply the face name of the font:
459 $font = Imager::Font->new(face=>'Arial Bold Italic');
461 There isn't any access to other logical font attributes, but this
462 typically isn't necessary for Win32 TrueType fonts, since you can
463 construct the full name of the font as above.
465 Other logical font attributes may be added if there is sufficient demand.
473 C<file> - name of the file to load the font from.
479 C<face> - face name. This is used only under Win32 to create a GDI based
480 font. This is ignored if the C<file> parameter is supplied.
484 C<type> - font driver to use. Currently the permitted values for this are:
490 C<tt> - FreeType 1.x driver. Supports TrueType (C<.ttf>) fonts.
494 =for stopwords strikethrough overline
496 C<t1> - T1 Lib driver. Supports Postscript Type 1 fonts. Allows for
497 synthesis of underline, strikethrough and overline.
501 C<ft2> - FreeType 2.x driver. Supports many different font formats.
502 Also supports the transform() method.
508 C<color> - the default color used with this font. Default: red.
512 C<size> - the default size used with this font. Default: 15.
516 C<utf8> - if non-zero then text supplied to $img->string(...) and
517 $font->bounding_box(...) is assumed to be UTF-8 encoded by default.
521 C<align> - the default value for the $img->string(...) C<align>
522 parameter. Default: 1.
526 C<vlayout> - the default value for the $img->string(...) C<vlayout>
527 parameter. Default: 0.
531 C<aa> - the default value for the $im->string(...) C<aa> parameter.
536 C<index> - for font file containing multiple fonts this selects which
537 font to use. This is useful for Macintosh C<DFON> (F<.dfont>) and suitcase
540 If you want to use a suitcase font you will need to tell Imager to use
541 the FreeType 2.x driver by setting C<type> to C<'ft2'>:
543 my $font = Imager::Font->new(file=>$file, index => 1, type=>'ft2')
544 or die Imager->errstr;
548 Returns the new font object on success. Returns C<undef> on failure
549 and sets an error message readable with C<< Imager->errstr >>.
553 Returns the bounding box for the specified string. Example:
562 $right_bearing) = $font->bounding_box(string => "A Fool");
564 my $bbox_object = $font->bounding_box(string => "A Fool");
570 the relative start of a the string. In some
571 cases this can be a negative number, in that case the first letter
572 stretches to the left of the starting position that is specified in
573 the string method of the Imager class
575 =item C<$global_descent>
577 how far down the lowest letter of the entire font reaches below the
578 baseline (this is often j).
582 how wide the string from
583 the starting position is. The total width of the string is
584 C<$pos_width-$neg_width>.
590 the same as <$global_descent> and <$global_ascent> except that they
591 are only for the characters that appear in the string.
593 =item C<$advance_width>
595 the distance from the start point that the next string output should
596 start at, this is often the same as C<$pos_width>, but can be
597 different if the final character overlaps the right side of its
600 =item C<$right_bearing>
602 The distance from the right side of the final glyph to the end of the
603 advance width. If the final glyph overflows the advance width this
608 Obviously we can stuff all the results into an array just as well:
610 @metrics = $font->bounding_box(string => "testing 123");
612 Note that extra values may be added, so $metrics[-1] isn't supported.
613 It's possible to translate the output by a passing coordinate to the
616 @metrics = $font->bounding_box(string => "testing 123", x=>45, y=>34);
618 This gives the bounding box as if the string had been put down at C<(x,y)>
619 By giving bounding_box 'canon' as a true value it's possible to measure
620 the space needed for the string:
622 @metrics = $font->bounding_box(string=>"testing",size=>15,canon=>1);
624 This returns the same values in $metrics[0] and $metrics[1],
627 $bbox[2] - horizontal space taken by glyphs
628 $bbox[3] - vertical space taken by glyphs
630 Returns an L<Imager::Font::BBox> object in scalar context, so you can
631 avoid all those confusing indexes. This has methods as named above,
632 with some extra convenience methods.
640 C<string> - the string to calculate the bounding box for. Required.
644 C<size> - the font size to use. Default: value set in
645 Imager::Font->new(), or 15.
649 C<sizew> - the font width to use. Default to the value of the C<size>
654 C<utf8> - For drivers that support it, treat the string as UTF-8 encoded.
655 For versions of perl that support Unicode (5.6 and later), this will
656 be enabled automatically if the 'string' parameter is already a UTF-8
657 string. See L</UTF-8> for more information. Default: the C<utf8> value
658 passed to Imager::Font->new(...) or 0.
662 C<x>, C<y> - offsets applied to @box[0..3] to give you a adjusted bounding
663 box. Ignored in scalar context.
667 C<canon> - if non-zero and the C<x>, C<y> parameters are not supplied,
668 then $pos_width and $global_ascent values will returned as the width
669 and height of the text instead.
673 On success returns either the list of bounds, or a bounding box object
674 in scalar context. Returns an empty list or C<undef> on failure and
675 sets an error message readable with C<< Imager->errstr >>.
677 The transformation matrix set by L</transform()> has no effect on the
678 result of this method - the bounds of the untransformed text is
683 The $img->string(...) method is now documented in
684 L<Imager::Draw/string()>
686 =item align(string=>$text,size=>$size,x=>...,y=>...,valign => ...,halign=>...)
688 Higher level text output - outputs the text aligned as specified
689 around the given point (x,y).
691 # "Hello" centered at 100, 100 in the image.
692 my ($left, $top, $right, $bottom) =
693 $font->align(string=>"Hello",
695 halign=>'center', valign=>'center',
698 Takes the same parameters as $font->draw(), and the following extra
705 C<valign> - Possible values are:
711 Point is at the top of the text.
715 Point is at the bottom of the text.
719 Point is on the baseline of the text (default.)
723 Point is vertically centered within the text.
735 C<left> - the point is at the left of the text.
739 C<start> - the point is at the start point of the text.
743 C<center> - the point is horizontally centered within the text.
747 C<right> - the point is at the right end of the text.
751 C<end> - the point is at the end point of the text.
757 C<image> - The image to draw to. Set to C<undef> to avoid drawing but
758 still calculate the bounding box.
762 Returns a list specifying the bounds of the drawn text on success.
763 Returns an empty list on failure, if an C<image> parameter was
764 supplied the error message can be read with C<< $image->errstr >>,
765 otherwise it's available as C<< Imager->errstr >>.
769 =item dpi(xdpi=>$xdpi, ydpi=>$ydpi)
773 Set or retrieve the spatial resolution of the image in dots per inch.
774 The default is 72 dpi.
776 This isn't implemented for all font types yet.
778 Possible parameters are:
784 C<xdpi>, C<ydpi> - set the horizontal and vertical resolution in dots
789 C<dpi> - set both horizontal and vertical resolution to this value.
793 Returns a list containing the previous C<xdpi>, C<ydpi> values on
794 success. Returns an empty list on failure, with an error message
795 returned in C<< Imager->errstr >>.
799 $font->transform(matrix=>$matrix);
801 Applies a transformation to the font, where matrix is an array ref of
802 numbers representing a 2 x 3 matrix:
804 [ $matrix->[0], $matrix->[1], $matrix->[2],
805 $matrix->[3], $matrix->[4], $matrix->[5] ]
807 Not all font types support transformations, these will return false.
809 It's possible that a driver will disable hinting if you use a
810 transformation, to prevent discontinuities in the transformations.
811 See the end of the test script t/t38ft2font.t for an example.
813 Currently only the ft2 (FreeType 2.x) driver supports the transform()
816 See samples/slant_text.pl for a sample using this function.
818 Note that the transformation is done in font co-ordinates where y
819 increases as you move up, not image co-ordinates where y decreases as
822 C<transform()> has no effect on the results of L</bounding_box()>.
824 Returns true on success. Returns false on failure with the cause
825 readable from C<< Imager->errstr >>.
827 =item has_chars(string=>$text)
829 Checks if the characters in $text are defined by the font.
831 In a list context returns a list of true or false value corresponding
832 to the characters in $text, true if the character is defined, false if
833 not. In scalar context returns a string of C<NUL> or non-C<NUL>
834 characters. Supports UTF-8 where the font driver supports UTF-8.
836 Not all fonts support this method (use $font->can("has_chars") to
839 On error, returns an empty list or undef in scalar context, and sets
840 an error message readable with C<< Imager->errstr >>.
846 C<string> - string of characters to check for. Required. Must contain
847 at least one character.
851 C<utf8> - For drivers that support it, treat the string as UTF-8
852 encoded. For versions of perl that support Unicode (5.6 and later),
853 this will be enabled automatically if the 'string' parameter is
854 already a UTF-8 string. See L</UTF-8> for more information. Default:
855 the C<utf8> value passed to Imager::Font->new(...) or 0.
861 Returns the internal name of the face. Not all font types support
862 this method yet, so you should check with C<< $font->can("face_name")
863 >> before calling C<face_name>.
865 =item glyph_names(string=>$string [, utf8=>$utf8 ][, reliable_only=>0 ] );
867 Returns a list of glyph names for each of the characters in the
868 string. If the character has no name then C<undef> is returned for
871 Some font files do not include glyph names, in this case FreeType 2
872 will not return any names. FreeType 1 can return standard names even
873 if there are no glyph names in the font.
875 FreeType 2 has an API function that returns true only if the font has
876 "reliable glyph names", unfortunately this always returns false for
877 TrueType fonts. This can avoid the check of this API by supplying
878 C<reliable_only> as 0. The consequences of using this on an unknown
879 font may be unpredictable, since the FreeType documentation doesn't
880 say how those name tables are unreliable, or how FT2 handles them.
882 Both FreeType 1.x and 2.x allow support for glyph names to not be
885 If the supplied C<string> is marked as UTF-8 or the C<utf8> parameter
886 is true and the supplied string does not contain valid UTF-8, returns
887 an empty string and set an error message readable from C<<
890 =item can_glyph_names()
892 As a class method, returns true if the underlying library supports
893 returning glyph names.
895 As an object method, returns true if the supplied font supports
896 returning glyph names.
900 This is used by Imager's string() method to implement drawing text.
901 See L<Imager::Draw/string()>.
905 =head1 MULTIPLE MASTER FONTS
907 The FreeType 2 driver supports multiple master fonts:
913 Test if the font is a multiple master font.
917 Returns a list of the axes that can be changes in the font. Each
918 entry is an array reference which contains:
928 minimum value for this axis.
932 maximum value for this axis
936 =item set_mm_coords(coords=>\@values)
938 Blends an interpolated design from the master fonts. @values must
939 contain as many values as there are axes in the font.
943 For example, to select the minimum value in each axis:
945 my @axes = $font->mm_axes;
946 my @coords = map $_->[1], @axes;
947 $font->set_mm_coords(coords=>\@coords);
949 It's possible other drivers will support multiple master fonts in the
950 future, check if your selected font object supports the is_mm() method
951 using the can() method.
955 There are 2 ways of rendering Unicode characters with Imager:
961 For versions of perl that support it, use perl's native UTF-8 strings.
962 This is the simplest method.
966 Hand build your own UTF-8 encoded strings. Only recommended if your
967 version of perl has no UTF-8 support.
971 Imager won't construct characters for you, so if want to output
972 Unicode character 00C3 "LATIN CAPITAL LETTER A WITH DIAERESIS", and
973 your font doesn't support it, Imager will I<not> build it from 0041
974 "LATIN CAPITAL LETTER A" and 0308 "COMBINING DIAERESIS".
976 To check if a driver supports UTF-8 call the utf8() method:
982 Return true if the font supports UTF-8.
986 =head2 Native UTF-8 Support
988 If your version of perl supports UTF-8 and the driver supports UTF-8,
989 just use the $im->string() method, and it should do the right thing.
991 =head2 Build your own
993 In this case you need to build your own UTF-8 encoded characters.
997 $x = pack("C*", 0xE2, 0x80, 0x90); # character code 0x2010 HYPHEN
999 You need to be careful with versions of perl that have UTF-8
1000 support, since your string may end up doubly UTF-8 encoded.
1004 $x = "A\xE2\x80\x90\x41\x{2010}";
1005 substr($x, -1, 0) = "";
1006 # at this point $x is has the UTF-8 flag set, but has 5 characters,
1007 # none, of which is the constructed UTF-8 character
1009 The test script t/t38ft2font.t has a small example of this after the
1012 # an attempt using emulation of UTF-8
1014 =head1 DRIVER CONTROL
1016 If you don't supply a 'type' parameter to Imager::Font->new(), but you
1017 do supply a 'file' parameter, Imager will attempt to guess which font
1018 driver to used based on the extension of the font file.
1020 Since some formats can be handled by more than one driver, a priority
1021 list is used to choose which one should be used, if a given format can
1022 be handled by more than one driver.
1028 The current priorities can be retrieved with:
1030 @drivers = Imager::Font->priorities();
1032 You can set new priorities and save the old priorities with:
1034 @old = Imager::Font->priorities(@drivers);
1036 If you supply driver names that are not currently supported, they will
1039 Imager supports both T1Lib and FreeType 2 for working with Type 1
1040 fonts, but currently only T1Lib does any caching, so by default T1Lib
1041 is given a higher priority. Since Imager's FreeType 2 support can also
1042 do font transformations, you may want to give that a higher priority:
1044 my @old = Imager::Font->priorities(qw(tt ft2 t1));
1048 Registers an extra font driver. Accepts the following parameters:
1054 type - a brief identifier for the font driver. You can supply this
1055 value to C<< Imager::Font->new() >> to create fonts of this type.
1060 class - the font class name. Imager will attempted to load this
1061 module by name. Required.
1065 files - a regular expression to match against file names. If supplied
1066 this must be a valid perl regular expression. If not supplied you can
1067 only create fonts of this type by supplying the C<type> parameter to
1068 C<< Imager::Font->new() >>
1072 description - a brief description of the font driver. Defaults to the
1073 value supplied in C<class>.
1081 Arnar M. Hrafnkelsson, addi@umich.edu
1082 And a great deal of help from others - see the F<README> for a complete
1087 The $pos_width member returned by the bounding_box() method has
1088 historically returned different values from different drivers. The
1089 FreeType 1.x and 2.x, and the Win32 drivers return the max of the
1090 advance width and the right edge of the right-most glyph. The Type 1
1091 driver always returns the right edge of the right-most glyph.
1093 The newer advance_width and right_bearing values allow access to any
1102 Imager(3), Imager::Font::FreeType2(3), Imager::Font::Type1(3),
1103 Imager::Font::Win32(3), Imager::Font::Truetype(3), Imager::Font::BBox(3)
1105 http://imager.perl.org/