perl cairo module

Back to cookbook

Install Cairo CPAN Module

Using CPAN:

    # cpan Cairo

Using CPANPLUS

    # cpanp -i Cairo

Examples

Draw Lines

    #!/usr/bin/perl

    use strict;
    use warnings;
    use Cairo;

    use constant
    {
        IMG_WIDTH => 640,
        IMG_HEIGHT => 480,
        PADDING => "10 10 10 10"  # top , right , bottom , left
    };

    die "png backend not supported" unless (Cairo::HAS_PNG_FUNCTIONS);

    my $png = shift || "dashed_rect.png";

    my $surf = Cairo::ImageSurface->create ('argb32', IMG_WIDTH, IMG_HEIGHT);
    my $cr = Cairo::Context->create ($surf);

    $cr->rectangle (0, 0, IMG_WIDTH, IMG_HEIGHT);
    $cr->set_source_rgba (1, 1, 1, 0.5);
    $cr->fill;


    my %padding;

    @padding{ qw/top right bottom left/ } = split /\s+/,PADDING;
    my @point = (
        [ $padding{left}, $padding{top} ] ,
        [ IMG_WIDTH - $padding{right} , $padding{top} ],
        [ IMG_WIDTH - $padding{right} , IMG_HEIGHT - $padding{bottom} ],
        [ $padding{left} , IMG_HEIGHT - $padding{bottom} ] ,
        [ $padding{left}, $padding{top} ] ,
    );



    $cr->save;
    $cr->set_source_rgba (0, 0, 0, 1 );
    $cr->set_line_width ( 3 );
    $cr->set_dash ( 0 , 50.0 , 10.0 , 10.0 , 10.0 );

    for my $i (  0 .. 3 )  {
            my $p = $point[$i] ;
            my $next_p = $point[ $i + 1 ];
            $cr->new_path;
            $cr->move_to (  @$p );
            $cr->line_to (  @$next_p );
            $cr->stroke;

    }

    $cr->restore;



    $surf->write_to_png ($png);