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',
23 class=>'Imager::Font::Type1',
24 module=>'Imager/Font/Type1.pm',
26 description => 'T1Lib',
29 class=>'Imager::Font::FreeType2',
30 module=>'Imager/Font/FreeType2.pm',
31 files=>'.*\.(pfa|pfb|otf|ttf|fon|fnt|dfont|pcf(\.gz)?)$',
32 description => 'FreeType 2.x',
35 class=>'Imager::Font::Image',
36 module=>'Imager/Font/Image.pm',
40 class=>'Imager::Font::W32',
41 module=>'Imager/Font/W32.pm',
42 description => 'Win32 GDI Fonts',
46 # this currently should only contain file based types, don't add w32
47 my @priority = qw(t1 tt ft2 ifs);
49 # when Imager::Font is loaded, Imager.xs has not been bootstrapped yet
50 # this function is called from Imager.pm to finish initialization
52 @priority = grep Imager::i_has_format($_), @priority;
53 for my $driver_name (grep Imager::i_has_format($_), keys %drivers) {
54 $drivers{$driver_name}{enabled} = 1;
59 # 1. start by checking if file is the parameter
60 # 1a. if so qualify path and compare to the cache.
61 # 2a. if in cache - take it's id from there and increment count.
67 my ($file, $type, $id);
68 my %hsh=(color => Imager::Color->new(255,0,0,0),
78 if (!defined($type) or !$drivers{$type} or !$drivers{$type}{enabled}) {
79 for my $drv (@priority) {
81 my $re = $drivers{$drv}{files} or next;
82 if ($file =~ /$re/i) {
88 if (!defined($type)) {
89 # some types we can support, but the driver isn't available
90 # work out which drivers support it, so we can provide the user
91 # some useful information on how to get it working
93 for my $driver_name (keys %drivers) {
94 my $driver = $drivers{$driver_name};
95 push @not_here, "$driver_name ($driver->{description})"
96 if $driver->{files} && $file =~ /$driver->{files}/i;
99 $Imager::ERRSTR = "No font drivers enabled that can support this file, rebuild Imager with any of ".join(", ", @not_here)." to use this font file";
102 $Imager::ERRSTR = "No font type found for $hsh{'file'}";
106 } elsif ($hsh{face}) {
109 $Imager::ERRSTR="No font file specified";
113 if (!$Imager::formats{$type}) {
114 $Imager::ERRSTR = "`$type' not enabled";
118 # here we should have the font type or be dead already.
120 require $drivers{$type}{module};
121 return $drivers{$type}{class}->new(%hsh);
124 # returns first defined parameter
127 return $_ if defined $_;
134 my %input = ('x' => 0, 'y' => 0, @_);
135 unless ($input{image}) {
136 $Imager::ERRSTR = 'No image supplied to $font->draw()';
139 my $image = $input{image};
140 $input{string} = _first($input{string}, $input{text});
141 unless (defined $input{string}) {
142 $image->_set_error("Missing required parameter 'string'");
145 $input{aa} = _first($input{aa}, $input{antialias}, $self->{aa}, 1);
146 # the original draw code worked this out but didn't use it
147 $input{align} = _first($input{align}, $self->{align});
148 $input{color} = _first($input{color}, $self->{color});
149 $input{color} = Imager::_color($input{'color'});
151 $input{size} = _first($input{size}, $self->{size});
152 unless (defined $input{size}) {
153 $image->_set_error("No font size provided");
156 $input{align} = _first($input{align}, 1);
157 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
158 $input{vlayout} = _first($input{vlayout}, $self->{vlayout}, 0);
160 my $result = $self->_draw(%input);
162 $image->_set_error($image->_error_as_msg());
170 my %input = ( halign => 'left', valign => 'baseline',
171 'x' => 0, 'y' => 0, @_ );
173 # image needs to be supplied, but can be supplied as undef
174 unless (exists $input{image}) {
175 Imager->_set_error("Missing required parameter 'image'");
179 my $errors_to = $input{image} || 'Imager';
181 my $text = _first($input{string}, $input{text});
182 unless (defined $text) {
183 $errors_to->_set_error("Missing required parameter 'string'");
187 my $size = _first($input{size}, $self->{size});
188 my $utf8 = _first($input{utf8}, 0);
190 my $bbox = $self->bounding_box(string=>$text, size=>$size, utf8=>$utf8);
191 my $valign = $input{valign};
193 unless $valign && $valign =~ /^(?:top|center|bottom|baseline)$/;
195 my $halign = $input{halign};
197 unless $halign && $halign =~ /^(?:left|start|center|end|right)$/;
202 if ($valign eq 'top') {
205 elsif ($valign eq 'center') {
206 $y += $bbox->ascent - $bbox->text_height / 2;
208 elsif ($valign eq 'bottom') {
209 $y += $bbox->descent;
211 # else baseline is the default
213 if ($halign eq 'left') {
214 $x -= $bbox->start_offset;
216 elsif ($halign eq 'start') {
219 elsif ($halign eq 'center') {
220 $x -= $bbox->start_offset + $bbox->total_width / 2;
222 elsif ($halign eq 'end') {
223 $x -= $bbox->advance_width;
225 elsif ($halign eq 'right') {
226 $x -= $bbox->advance_width - $bbox->right_bearing;
232 delete @input{qw/x y/};
233 $self->draw(%input, 'x' => $x, 'y' => $y, align=>1)
237 return ($x+$bbox->start_offset, $y-$bbox->ascent,
238 $x+$bbox->end_offset, $y-$bbox->descent+1);
245 if (!exists $input{'string'}) {
246 $Imager::ERRSTR='string parameter missing';
249 $input{size} ||= $self->{size};
250 $input{sizew} = _first($input{sizew}, $self->{sizew}, 0);
251 $input{utf8} = _first($input{utf8}, $self->{utf8}, 0);
253 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 cannoical (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";
319 @priority = grep Imager::i_has_format($_), @_;
330 Imager::Font - Font handling for Imager.
336 $t1font = Imager::Font->new(file => 'pathtofont.pfb');
337 $ttfont = Imager::Font->new(file => 'pathtofont.ttf');
338 $w32font = Imager::Font->new(face => 'Times New Roman');
340 $blue = Imager::Color->new("#0000FF");
341 $font = Imager::Font->new(file => 'pathtofont.ttf',
352 $right_bearing) = $font->bounding_box(string=>"Foo");
354 my $bbox_object = $font->bounding_box(string=>"Foo");
356 # documented in Imager::Draw
357 $img->string(font => $font,
367 =for stopwords TrueType FreeType
369 This module handles creating Font objects used by Imager. The module
370 also handles querying fonts for sizes and such. If both T1lib and
371 FreeType were available at the time of compilation then Imager should
372 be able to work with both TrueType fonts and t1 Postscript fonts. To
373 check if Imager is t1 or TrueType capable you can use something like
377 print "Has truetype" if $Imager::formats{tt};
378 print "Has t1 postscript" if $Imager::formats{t1};
379 print "Has Win32 fonts" if $Imager::formats{w32};
380 print "Has Freetype2" if $Imager::formats{ft2};
386 This creates a font object to pass to functions that take a font argument.
388 $font = Imager::Font->new(file => 'denmark.ttf',
394 This creates a font which is the TrueType font F<denmark.ttf>. It's
395 default color is $blue, default size is 30 pixels and it's rendered
396 anti-aliased by default. Imager can see which type of font a file is
397 by looking at the suffix of the file name for the font. A suffix of
398 C<ttf> is taken to mean a TrueType font while a suffix of C<pfb> is
399 taken to mean a Type 1 Postscript font. If Imager cannot tell which
400 type a font is you can tell it explicitly by using the C<type>
403 $t1font = Imager::Font->new(file => 'fruitcase', type => 't1');
404 $ttfont = Imager::Font->new(file => 'arglebarf', type => 'tt');
406 The C<index> parameter is used to select a single face from a font
407 file containing more than one face, for example, from a Macintosh font
408 suitcase or a C<.dfont> file.
410 If any of the C<color>, C<size> or C<aa> parameters are omitted when
411 calling C<< Imager::Font->new() >> the they take the following values:
413 color => Imager::Color->new(255, 0, 0, 0); # this default should be changed
418 To use Win32 fonts supply the face name of the font:
420 $font = Imager::Font->new(face=>'Arial Bold Italic');
422 There isn't any access to other logical font attributes, but this
423 typically isn't necessary for Win32 TrueType fonts, since you can
424 construct the full name of the font as above.
426 Other logical font attributes may be added if there is sufficient demand.
434 C<file> - name of the file to load the font from.
440 C<face> - face name. This is used only under Win32 to create a GDI based
441 font. This is ignored if the C<file> parameter is supplied.
445 C<type> - font driver to use. Currently the permitted values for this are:
451 C<tt> - FreeType 1.x driver. Supports TrueType (C<.ttf>) fonts.
455 =for stopwords strikethrough overline
457 C<t1> - T1 Lib driver. Supports Postscript Type 1 fonts. Allows for
458 synthesis of underline, strikethrough and overline.
462 C<ft2> - FreeType 2.x driver. Supports many different font formats.
463 Also supports the transform() method.
469 C<color> - the default color used with this font. Default: red.
473 C<size> - the default size used with this font. Default: 15.
477 C<utf8> - if non-zero then text supplied to $img->string(...) and
478 $font->bounding_box(...) is assumed to be UTF-8 encoded by default.
482 C<align> - the default value for the $img->string(...) C<align>
483 parameter. Default: 1.
487 C<vlayout> - the default value for the $img->string(...) C<vlayout>
488 parameter. Default: 0.
492 C<aa> - the default value for the $im->string(...) C<aa> parameter.
497 C<index> - for font file containing multiple fonts this selects which
498 font to use. This is useful for Macintosh C<DFON> (F<.dfont>) and suitcase
501 If you want to use a suitcase font you will need to tell Imager to use
502 the FreeType 2.x driver by setting C<type> to C<'ft2'>:
504 my $font = Imager::Font->new(file=>$file, index => 1, type=>'ft2')
505 or die Imager->errstr;
513 Returns the bounding box for the specified string. Example:
522 $right_bearing) = $font->bounding_box(string => "A Fool");
524 my $bbox_object = $font->bounding_box(string => "A Fool");
530 the relative start of a the string. In some
531 cases this can be a negative number, in that case the first letter
532 stretches to the left of the starting position that is specified in
533 the string method of the Imager class
535 =item C<$global_descent>
537 how far down the lowest letter of the entire font reaches below the
538 baseline (this is often j).
542 how wide the string from
543 the starting position is. The total width of the string is
544 C<$pos_width-$neg_width>.
550 the same as <$global_descent> and <$global_ascent> except that they
551 are only for the characters that appear in the string.
553 =item C<$advance_width>
555 the distance from the start point that the next string output should
556 start at, this is often the same as C<$pos_width>, but can be
557 different if the final character overlaps the right side of its
560 =item C<$right_bearing>
562 The distance from the right side of the final glyph to the end of the
563 advance width. If the final glyph overflows the advance width this
568 Obviously we can stuff all the results into an array just as well:
570 @metrics = $font->bounding_box(string => "testing 123");
572 Note that extra values may be added, so $metrics[-1] isn't supported.
573 It's possible to translate the output by a passing coordinate to the
576 @metrics = $font->bounding_box(string => "testing 123", x=>45, y=>34);
578 This gives the bounding box as if the string had been put down at C<(x,y)>
579 By giving bounding_box 'canon' as a true value it's possible to measure
580 the space needed for the string:
582 @metrics = $font->bounding_box(string=>"testing",size=>15,canon=>1);
584 This returns the same values in $metrics[0] and $metrics[1],
587 $bbox[2] - horizontal space taken by glyphs
588 $bbox[3] - vertical space taken by glyphs
590 Returns an L<Imager::Font::BBox> object in scalar context, so you can
591 avoid all those confusing indexes. This has methods as named above,
592 with some extra convenience methods.
600 C<string> - the string to calculate the bounding box for. Required.
604 C<size> - the font size to use. Default: value set in
605 Imager::Font->new(), or 15.
609 C<sizew> - the font width to use. Default to the value of the C<size>
614 C<utf8> - For drivers that support it, treat the string as UTF-8 encoded.
615 For versions of perl that support Unicode (5.6 and later), this will
616 be enabled automatically if the 'string' parameter is already a UTF-8
617 string. See L<UTF-8> for more information. Default: the C<utf8> value
618 passed to Imager::Font->new(...) or 0.
622 C<x>, C<y> - offsets applied to @box[0..3] to give you a adjusted bounding
623 box. Ignored in scalar context.
627 C<canon> - if non-zero and the C<x>, C<y> parameters are not supplied,
628 then $pos_width and $global_ascent values will returned as the width
629 and height of the text instead.
635 The $img->string(...) method is now documented in
636 L<Imager::Draw/string>
638 =item align(string=>$text,size=>$size,x=>...,y=>...,valign => ...,halign=>...)
640 Higher level text output - outputs the text aligned as specified
641 around the given point (x,y).
643 # "Hello" centered at 100, 100 in the image.
644 my ($left, $top, $right, $bottom) =
645 $font->align(string=>"Hello",
647 halign=>'center', valign=>'center',
650 Takes the same parameters as $font->draw(), and the following extra
657 C<valign> - Possible values are:
663 Point is at the top of the text.
667 Point is at the bottom of the text.
671 Point is on the baseline of the text (default.)
675 Point is vertically centered within the text.
687 C<left> - the point is at the left of the text.
691 C<start> - the point is at the start point of the text.
695 C<center> - the point is horizontally centered within the text.
699 C<right> - the point is at the right end of the text.
703 C<end> - the point is at the end point of the text.
709 C<image> - The image to draw to. Set to C<undef> to avoid drawing but
710 still calculate the bounding box.
714 Returns a list specifying the bounds of the drawn text.
718 =item dpi(xdpi=>$xdpi, ydpi=>$ydpi)
722 Set or retrieve the spatial resolution of the image in dots per inch.
723 The default is 72 dpi.
725 This isn't implemented for all font types yet.
727 Possible parameters are:
733 C<xdpi>, C<ydpi> - set the horizontal and vertical resolution in dots
738 C<dpi> - set both horizontal and vertical resolution to this value.
742 Returns a list containing the previous C<xdpi>, C<ydpi> values.
744 =item transform(matrix=>$matrix)
746 Applies a transformation to the font, where matrix is an array ref of
747 numbers representing a 2 x 3 matrix:
749 [ $matrix->[0], $matrix->[1], $matrix->[2],
750 $matrix->[3], $matrix->[4], $matrix->[5] ]
752 Not all font types support transformations, these will return false.
754 It's possible that a driver will disable hinting if you use a
755 transformation, to prevent discontinuities in the transformations.
756 See the end of the test script t/t38ft2font.t for an example.
758 Currently only the ft2 (FreeType 2.x) driver supports the transform()
761 See samples/slant_text.pl for a sample using this function.
763 Note that the transformation is done in font co-ordinates where y
764 increases as you move up, not image co-ordinates where y decreases as
767 =item has_chars(string=>$text)
769 Checks if the characters in $text are defined by the font.
771 In a list context returns a list of true or false value corresponding
772 to the characters in $text, true if the character is defined, false if
773 not. In scalar context returns a string of C<NUL> or non-C<NUL>
774 characters. Supports UTF-8 where the font driver supports UTF-8.
776 Not all fonts support this method (use $font->can("has_chars") to
783 C<string> - string of characters to check for. Required. Must contain
784 at least one character.
788 C<utf8> - For drivers that support it, treat the string as UTF-8
789 encoded. For versions of perl that support Unicode (5.6 and later),
790 this will be enabled automatically if the 'string' parameter is
791 already a UTF-8 string. See L<UTF-8> for more information. Default:
792 the C<utf8> value passed to Imager::Font->new(...) or 0.
798 Returns the internal name of the face. Not all font types support
801 =item glyph_names(string=>$string [, utf8=>$utf8 ][, reliable_only=>0 ] );
803 Returns a list of glyph names for each of the characters in the
804 string. If the character has no name then C<undef> is returned for
807 Some font files do not include glyph names, in this case FreeType 2
808 will not return any names. FreeType 1 can return standard names even
809 if there are no glyph names in the font.
811 FreeType 2 has an API function that returns true only if the font has
812 "reliable glyph names", unfortunately this always returns false for
813 TrueType fonts. This can avoid the check of this API by supplying
814 C<reliable_only> as 0. The consequences of using this on an unknown
815 font may be unpredictable, since the FreeType documentation doesn't
816 say how those name tables are unreliable, or how FT2 handles them.
818 Both FreeType 1.x and 2.x allow support for glyph names to not be
823 This is used by Imager's string() method to implement drawing text.
824 See L<Imager::Draw/string>.
828 =head1 MULTIPLE MASTER FONTS
830 The FreeType 2 driver supports multiple master fonts:
836 Test if the font is a multiple master font.
840 Returns a list of the axes that can be changes in the font. Each
841 entry is an array reference which contains:
851 minimum value for this axis.
855 maximum value for this axis
859 =item set_mm_coords(coords=>\@values)
861 Blends an interpolated design from the master fonts. @values must
862 contain as many values as there are axes in the font.
866 For example, to select the minimum value in each axis:
868 my @axes = $font->mm_axes;
869 my @coords = map $_->[1], @axes;
870 $font->set_mm_coords(coords=>\@coords);
872 It's possible other drivers will support multiple master fonts in the
873 future, check if your selected font object supports the is_mm() method
874 using the can() method.
878 There are 2 ways of rendering Unicode characters with Imager:
884 For versions of perl that support it, use perl's native UTF-8 strings.
885 This is the simplest method.
889 Hand build your own UTF-8 encoded strings. Only recommended if your
890 version of perl has no UTF-8 support.
894 Imager won't construct characters for you, so if want to output
895 Unicode character 00C3 "LATIN CAPITAL LETTER A WITH DIAERESIS", and
896 your font doesn't support it, Imager will I<not> build it from 0041
897 "LATIN CAPITAL LETTER A" and 0308 "COMBINING DIAERESIS".
899 To check if a driver supports UTF-8 call the utf8() method:
905 Return true if the font supports UTF-8.
909 =head2 Native UTF-8 Support
911 If your version of perl supports UTF-8 and the driver supports UTF-8,
912 just use the $im->string() method, and it should do the right thing.
914 =head2 Build your own
916 In this case you need to build your own UTF-8 encoded characters.
920 $x = pack("C*", 0xE2, 0x80, 0x90); # character code 0x2010 HYPHEN
922 You need to be be careful with versions of perl that have UTF-8
923 support, since your string may end up doubly UTF-8 encoded.
927 $x = "A\xE2\x80\x90\x41\x{2010}";
928 substr($x, -1, 0) = "";
929 # at this point $x is has the UTF-8 flag set, but has 5 characters,
930 # none, of which is the constructed UTF-8 character
932 The test script t/t38ft2font.t has a small example of this after the
935 # an attempt using emulation of UTF-8
937 =head1 DRIVER CONTROL
939 If you don't supply a 'type' parameter to Imager::Font->new(), but you
940 do supply a 'file' parameter, Imager will attempt to guess which font
941 driver to used based on the extension of the font file.
943 Since some formats can be handled by more than one driver, a priority
944 list is used to choose which one should be used, if a given format can
945 be handled by more than one driver.
951 The current priorities can be retrieved with:
953 @drivers = Imager::Font->priorities();
955 You can set new priorities and save the old priorities with:
957 @old = Imager::Font->priorities(@drivers);
961 If you supply driver names that are not currently supported, they will
964 Imager supports both T1Lib and FreeType 2 for working with Type 1
965 fonts, but currently only T1Lib does any caching, so by default T1Lib
966 is given a higher priority. Since Imager's FreeType 2 support can also
967 do font transformations, you may want to give that a higher priority:
969 my @old = Imager::Font->priorities(qw(tt ft2 t1));
973 Arnar M. Hrafnkelsson, addi@umich.edu
974 And a great deal of help from others - see the F<README> for a complete
979 You need to modify this class to add new font types.
981 The $pos_width member returned by the bounding_box() method has
982 historically returned different values from different drivers. The
983 FreeType 1.x and 2.x, and the Win32 drivers return the max of the
984 advance width and the right edge of the right-most glyph. The Type 1
985 driver always returns the right edge of the right-most glyph.
987 The newer advance_width and right_bearing values allow access to any
996 Imager(3), Imager::Font::FreeType2(3), Imager::Font::Type1(3),
997 Imager::Font::Win32(3), Imager::Font::Truetype(3), Imager::Font::BBox(3)
999 http://imager.perl.org/