Perl Cairo tutorial - Draw text

This is one page of a Perl Cairo tutorial.

This shows setting a font using select_font_face and set_font_size and drawing text using show_text. As can be seen, the text is positioned above and to the right of where we have moved to.
#!/usr/bin/perl
use warnings;
use strict;
use Cairo;
my $size = 400;
my $surface = Cairo::ImageSurface->create ('argb32', $size, $size);
my $cr = Cairo::Context->create ($surface);
$cr->rectangle (0, 0, $size, $size);
$cr->set_source_rgb (0.9, 0.9, 0.9);
$cr->fill ();
# Draw a grid
$cr->set_source_rgb (0.4, 0.4, 1);
$cr->set_line_width (2);
for my $i (1..3) {
    $cr->move_to (($size * $i)/4, 0);
    $cr->line_to (($size * $i)/4, $size);
    $cr->move_to (0, ($size * $i)/4);
    $cr->line_to ($size, ($size * $i)/4);
}
$cr->stroke ();
# Set the font
$cr->select_font_face ('sans', 'normal', 'bold');
# Set the size of the font
$cr->set_font_size ($size/4);
# Set the colour to "black".
$cr->set_source_rgb (0, 0, 0);
$cr->move_to ($size/4, $size/4);
# Draw text at the specified position
$cr->show_text ("Cairo");
# We have to call "fill" before we change the colour.
$cr->fill ();
# Set the colour to "red".
$cr->set_source_rgb (1, 0, 0);
# Draw text at the specified position
$cr->move_to ($size/4, (3*$size)/4);
$cr->show_text ("Larry");
$cr->fill ();

my $png = 'simple-text.png';
$surface->write_to_png ($png);

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer