Re: Auto-adjusting image



Hello.

Using GtkImage for these kind of tasks is really not the optimal
solution, since GtkImage is meant to be used for fixed-sized images.
It would be better to use GtkDrawingArea for this task and manually
paint pixbuf onto it. This is sample code that demonstrates how to do
this using Cairo.

------------------
#!/usr/bin/perl

use strict;
use warnings;
use Glib qw/TRUE FALSE/;
use Gtk2 -init;
use Cairo;

sub expose
{
   my ( $widget, $event, $pix ) = @_;

   my ( $ww, $wh ) = $event->window->get_size();
   my $iw = $pix->get_width();
   my $ih = $pix->get_height();

   my $scale_x = $ww / $iw;
   my $scale_y = $wh / $ih;

   my $scale = $scale_x < $scale_y ? $scale_x : $scale_y;
   my $x_off = ( $ww - $iw * $scale ) / 2;
   my $y_off = ( $wh - $ih * $scale ) / 2;

   my $cr = Gtk2::Gdk::Cairo::Context->create( $event->window );
   $cr->translate( $x_off, $y_off );
   $cr->scale( $scale, $scale );
   $cr->set_source_pixbuf( $pix, 0, 0 );
   $cr->paint();

   return TRUE;
}

sub quit_program
{
   Gtk2->main_quit();
}

my $window = Gtk2::Window->new('toplevel');
$window->set_border_width(10);
$window->signal_connect(destroy => \&quit_program);

my $hbox = Gtk2::HBox->new(FALSE, 10);

my $label = Gtk2::Label->new('Test');

my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file('background.png');
my $image = Gtk2::DrawingArea->new();
$image->signal_connect('expose-event' => \&expose, $pixbuf);

$hbox->pack_start($label, FALSE, FALSE, 10);
$hbox->pack_start($image, TRUE, TRUE, 10);

$window->add($hbox);
$window->show_all();

Gtk2->main();
-------------------------------

Tadej

-- 
Tadej BorovÅak
tadeboro.blogspot.com
tadeboro gmail com
tadej borovsak gmail com



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]