首页 > 解决方案 > 无法在 GooCanvas 中画线

问题描述

在 Perl/Gtk3 脚本中并使用 GooCanvas,我可以轻松地绘制一个矩形、一个省略号或其他任何东西,但似乎不可能绘制一条简单的线。

通过调用 Goo::CanvasPolyline->new() 绘制线条。该线的坐标由调用 Goo::CanvasPoints->new() 指定,但该调用会产生以下错误:

GLib-ERROR **: ../../../../glib/gmem.c:105: failed to allocate 18446744069314558208 bytes at /usr/lib/x86_64-linux-gnu/perl5/5.26/Glib/Object/Introspection.pm line 67.
Aborted (core dumped)

我尝试过 Perl 模块 Goo::Canvas 和更现代的 GooCanvas2;两者都产生相同的错误。

我找不到任何有效的代码示例;只是谷歌在 $RANDOM_WEBSITE 上找到的下面的非工作脚本。

#!/usr/bin/perl -w
use strict;
use warnings;
use Gtk3 -init;

Glib::Object::Introspection->setup(basename => 'GooCanvas', version => '2.0', package => 'Goo');


my $window = Gtk3::Window->new('toplevel');
$window->signal_connect('delete_event' => sub { Gtk2->main_quit; });
$window->set_size_request(640, 600);
$window->set_title("Gtk3 GooCanvas with Perl Gobject Introspection");
$window->signal_connect(destroy => sub { Gtk3->main_quit });

my $swin = Gtk3::ScrolledWindow->new;
$swin->set_shadow_type('in');
$window->add($swin);

my $canvas = Goo::Canvas->new; # Gobject Introspection of Gtk3 Goo version
$canvas->set_size_request(800, 650);
$canvas->set_bounds(0, 0, 1000, 1000);
$swin->add($canvas);
my $root = $canvas->get_root_item();

# first point set
my $pts_ref = [50,50,180,120,90,100,50,50];

my $points = Goo::CanvasPoints->new(
         $pts_ref,
         );

my $line = Goo::CanvasPolyline->new(
   'parent' => $root,
   'close-path' => 0,
   'points' => $points, #in Gtk2 could just use $pts_ref
   'stroke-color' => 'black',
   'line-width' => 3,
);


my $ellipse = Goo::CanvasEllipse->new(
   'parent' => $root,
   'center-x' => 20,  
   'center-y' => 20,  
   'width'  =>  +60,
   'height' =>  +60,  
   'stroke-color' => 'goldenrod',
   'line-width' => 8,
   'fill-color-rgba' => 0x3cb37180,
);


$root->translate(200,200);

$window->show_all();
Gtk3->main;
__END__ 

标签: perlcanvasgtk

解决方案


my $points = Goo::CanvasPoints->new( $pts_ref );

根据文档,构造函数应该采用要保留的点数,而不是对点数组的引用。所以你可以尝试:

[...]
# first point set
my $pts_ref = [50,50,180,120,90,100,50,50];
my $num_points = (scalar @$pts_ref)/2;
my $points = Goo::CanvasPoints->new( $num_points );

# Set the points:
my $j = 0;
for my $i (0..($num_points -1)) {
    my $x = $pts_ref->[$j];
    my $y = $pts_ref->[$j+1];
    $points->set_point($i, $x, $y);
    $j += 2;
}
[...]

推荐阅读