Deal all!
I continue my experiments with SDL. I found some old thread somewhere and
now I have a button-like image that switches its appearance when I hover
over it (with the mouse).
Here are the questions:
a) Is the code attached the recommended way to do it or should it be done in
another fashion?
b) I would like to add an action, when someone clicks the button. In
Tk-terminology, this would be a callback. Any suggestions on how I should do
this?
Best regards,
Alex
[code]
#!perl
package My::SimpleButton;
use strict;
use warnings;
use SDL;
use SDLx::Rect;
use Data::Dumper qw/Dumper/;
=head1
=cut
sub new {
my ($class,@params) = @_;
my $self = {};
bless($self,$class);
for(qw(ID APP X Y IMG IMGHV IMGPRESSED)){
$self->{$_} = shift(@params);
}
$self->{HV} = 0;
$self->draw($self->{IMG});
return($self);
}
sub draw{
my ($self, $img) = @_;
my $frame_rect = SDLx::Rect->new(0, 0, $img->width(), $img->height());
my $dest_rect = SDLx::Rect->new(
$self->{X},
$self->{Y},
$img->width(),
$img->height(),
);
$self->{APP}->blit_by($img, [0, 0, $img->width(), $img->height()], [
$self->{X},
$self->{Y},
$img->width(),
$img->height(),
]);
$self->{APP}->update();
return 1;
}
sub check{
my ($self,$mx,$my,$event) = @_;
my $img = $self->{IMG};
#Hover - Effekt
if( $mx > $self->{X} &&
$mx < ($self->{X}+ $img->width) &&
$my > $self->{Y} &&
$my < ($self->{Y}+ $img->height) ){
if( !$self->{HV} ) {
$self->{HV} = 1;
$self->draw($self->{IMGHV});
}
} else {
if($self->{HV}) {
$self->{HV}=0;
$self->draw($self->{IMG});
}
return 0;
}
return;
}
=head1 CREDITS
c.f. L<http://www.perl-community.de/bat/poard/thread/7847>
=cut
1; # /My::SimpleButton
use SDL;
use SDLx::App;
use SDL::Event;
use SDL::Events;
use SDLx::Surface;
use SDL::Color;
my $app = SDLx::App->new(
w => 640,
h => 400,
exit_on_quit => 1,
);
$app->add_event_handler( \&quit_event );
$app->add_event_handler( \&mnouseover );
my $img = SDLx::Surface->load( 'images/blueOpera_1.png' );
my $img2 = SDLx::Surface->load( 'images/blueOpera_2.png' );
my $img3 = SDLx::Surface->load( 'images/redOpera_2.png' );
my $SimpleButton = My::SimpleButton->new(1, $app, 65, 25, $img, $img2,
$img3);
$app->run();
sub quit_event {
#The callback is provided a SDL::Event to use
my $event = shift;
#Each event handler also returns you back the Controller call it
my $controller = shift;
#Stopping the controller for us will exit $app->run() for us
$controller->stop if $event->type == SDL_QUIT;
} # /quit_event
sub mnouseover {
#The callback is provided a SDL::Event to use
my $event = shift;
#Each event handler also returns you back the Controller call it
my $controller = shift;
if( $event->type == SDL_MOUSEMOTION ) {
my $click = $SimpleButton->check($event->motion_x,
$event->motion_y,$event);
}
} # /mnouseover
exit(0);
[/code]