显示动画图像


use warnings;
use Tk;
use Tk::Animation;
my $scr = new MainWindow;
$scr->configure(-background=>"black");
$scr->geometry("200x100");
my $canvas = $scr->Canvas(-width,200,-height,100,-background=>"black")
                 ->pack(-expand,1,-fill,'both');
my $image  = $scr->Animation('-format' => 'gif', -file=>"help.gif" );
$canvas->createImage( 50,50, -image=> $image);
$image->start_animation(500);
MainLoop;

我希望图像在我的窗口中上下移动。现在我应该在此代码中添加什么?

Tk::Animation 只负责 Gif 文件的动画。在这种情况下,动画意味着一直更改帧。因此,移动仅限于图像内容本身。

如果要在画布上将图像作为一个整体移动,则必须使用 move 方法。当然,这可以与 gif 动画结合使用。

下面是一个 gif 从左向右移动的示例:

#!perl
use strict;
use warnings;
use Tk;
use Tk::Animation;
my $mw = MainWindow->new();
$mw->configure(-background=>"black");
$mw->geometry("200x100");
my $canvas = $mw->Canvas(
    -width => 200,
    -height => 100,
    -background => 'black',
)->pack(
    -expand => 1,
    -fill => 'both',
);
my $image  = $mw->Animation(
    -format => 'gif',
    -file => 'oi.gif',
    # please use this one: http://images1.wikia.nocookie.net/vaultarmory/images/2/23/Gif_dancinggir.gif
);
# -- clear transparent background while drawing
$image->set_disposal_method( 1 );
my $id_of_image_in_canvas = $canvas->createImage(
    50, 50,
    -image=> $image,
);
$image->start_animation(80);
# -- store the current mving direction
my $direction = 'moving2left';
$mw->repeat(600, &move_item_in_canvas);
$mw->MainLoop();
exit(0);

sub move_item_in_canvas {
    # -- get current location
    my ($x1, $y1, $x2, $y2) = $canvas->bbox($id_of_image_in_canvas);
    # -- compute if to move left or right
    my $min_left = 0;
    my $max_right = 200;
    if( $direction eq 'moving2left' && $x1 > $min_left ) {
        # continue moving left
        $canvas->move($id_of_image_in_canvas, -10, 0);
    }elsif( $direction eq 'moving2left' && $x1 <= $min_left ) {
        # change direction, move to the right
        $direction = 'moving2right';
        $canvas->move($id_of_image_in_canvas, 10, 0);
    }elsif( $direction eq 'moving2right' && $x2 < $max_right ) {
        # move right
        $canvas->move($id_of_image_in_canvas, 10, 0);
    }elsif( $direction eq 'moving2right' && $x2 >= $max_right ){
        # change direction, move to the left
        $direction = 'moving2left';
        $canvas->move($id_of_image_in_canvas, -10, 0);
    }else{
        die('Error: don't know what to do in this case.');
    }
    return;
} # /move_item_in_canvas

最新更新