[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Some help needed with object oriented perl!



Charles,

Because $im (the variable) contains a reference to
the GD::Image object, passing it by value is all
you need to work with the object inside the 
subroutine.  Your example

  sub drawstar
    my ($im, $x, $y, $d) = @_;

is exactly what you want.  Inside the subroutine, you
can use the lexically-local variable $im (containing a 
reference to the same object) to invoke the object's 
methods, as in:

    $im->line($x, $y, $x+$d, $y+d, $black);

The object itself is updated by these method calls, so
there is no need to return anything.  After the subroutine
returns, the original variable $im is used to access the
updated object, as in:

  print F $im->gif;

Here's a version of drawstar that draws an asterisk-like
figure.


sub drawstar {
    my ($im, $x, $y, $d) = @_;
    # draw a star using graphics primitives on $im

    my $white = $im->colorAllocate(255,255,255);
    my $black = $im->colorAllocate(0,0,0);
    
    my $r = $d / 2;
    my $s = int sqrt($r * $r / 2);
    my ($w, $h) = $im->getBounds();
    
    $im->filledRectangle(0, 0, $h, $w, $white); # white background

    $im->line($x, $y-$r, $x, $y+$r, $black); # vertical
    $im->line($x-$r, $y, $x+$r, $y, $black); # horizontal
    $im->line($x-$s, $y-$s, $x+$s, $y+$s, $black); # diagonal
    $im->line($x-$s, $y+$s, $x+$s, $y-$s, $black); # diagonal
}

Hope this helps.

Jim



At 9:54 AM +1000 9/14/99, Charles Cave wrote:
>I was wondering if someone could give some help
>on passing variables by reference.  My specific need
>is with the GD graphics programming.
>
>Some background: An image is created with this line:
>    $im = new GD::Image(200, 200);
>I would like to write a subroutine that takes the reference
>to the object ($im in this case), and some arguments,
>then do the necessary drawing. After the subroutine call,
>$im object will have been updated.
>
>For example, if I write a subroutine to draw a five pointed
>star, how do I reference $im in the subroutine?  I read
>some documentation from www.perl.com and I am more
>confused than ever!
>
>I know that \$im is a reference to the variable $im, but
>I understand that in my example, $im is a pointer to an object
>of type GD::Image!
>
>
>Code fragments:
>
>$im = new GD::Image(200, 200);
>&drawstar($im, 100, 100, 20);
># output the $im to file
>
>sub drawstar {
>  my ($im, $x, $y, $d) = @_;    # <- is this line correct?
># draw a star using graphics primitives on $im
>  return;
>}
>
>
>Thank you,
>Charles Cave
>charles@irg.com.au
>
>===== Want to unsubscribe from this list?
>===== Send mail with body "unsubscribe" to macperl-request@macperl.org

--
Jim Miner          jfm@winternet.com

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org