在wxFrame上平铺位图

问题描述 投票:1回答:2

我想使用wxPerl在带有平铺位图的帧上设置背景。借助wxWidgets中的示例,我提出了以下代码。不幸的是,它什么也没做,框架保持空白。这是否是正确的方法,还是还有其他方法?

use warnings;
use strict;

package MyFrame;
use Wx qw(:everything);
use base qw( Wx::Frame );

sub new {
    my ( $class, $path ) = @_;
    my $self
        = $class->SUPER::new( undef, -1, 'Test', [ -1, -1 ], [ 600, 400 ], );
    $self->set_tiling_background($path);
    return $self;
}

sub set_tiling_background {
    my ( $self, $path ) = @_;

    ## Create a wxBitmap from the file
    my $file = IO::File->new($path);
    binmode $file;

    my $handler = Wx::BMPHandler->new();
    my $image   = Wx::Image->new();
    $handler->LoadFile( $image, $file );
    my $bitmap = Wx::Bitmap->new($image);

    ## Just to check that the bitmap is good.
    $bitmap->SaveFile('saved.bmp', wxBITMAP_TYPE_BMP);

    ## Draw the bitmap tiling over the frame
    ## https://github.com/wxWidgets/wxWidgets/blob/master/src/html/htmlwin.cpp
    my $dc = Wx::WindowDC->new($self);

    my $size_x = $bitmap->GetWidth;
    my $size_y = $bitmap->GetHeight;

    for ( my $x = 0; $x < 600; $x += $size_x ) {
        for ( my $y = 0; $y < 400; $y += $size_y ) {
            $dc->DrawBitmap( $bitmap, $x, $y, 0 );
        }
    }
}

package MyApp;
use base 'Wx::App';
my $path = '/path/to/bitmap.bmp';

sub OnInit {
    my ($self) = @_;
    my $frame = MyFrame->new($path);
    $frame->Show(1);
}

package main;
MyApp->new->MainLoop;

perl wxwidgets wxperl
2个回答
2
投票

这里是使用ERASE_BACKGROUND事件处理程序的示例:

package MyFrame;
use Wx qw(:everything wxBITMAP_TYPE_JPEG);
use base qw( Wx::Frame );
use feature qw(say);
use strict;
use warnings;
use Wx::Event;

sub new {
    my ( $class, $path ) = @_;
    my $self
        = $class->SUPER::new( undef, -1, 'Test', [ -1, -1 ], [ 600, 400 ], );
    my $bitmap = Wx::Bitmap->new( $path , wxBITMAP_TYPE_JPEG );
    Wx::Event::EVT_ERASE_BACKGROUND( $self, sub { $self->setBgImage( $bitmap, @_) });
    return $self;
}

sub setBgImage {
    my ( $self, $bitmap, $frame, $evt ) = @_;

    return if !defined $evt;
    my $dc = $evt->GetDC();
    my $size_x = $bitmap->GetWidth;
    my $size_y = $bitmap->GetHeight;

    for ( my $x = 0; $x < 600; $x += $size_x ) {
        for ( my $y = 0; $y < 400; $y += $size_y ) {
            $dc->DrawBitmap( $bitmap, $x, $y, 0 );
        }
    }
}

package MyApp;
use base 'Wx::App';
my $path = 'logo.jpg';

sub OnInit {
    my ($self) = @_;
    my $frame = MyFrame->new($path);
    $frame->Show(1);
}

package main;
MyApp->new->MainLoop;

这给我在Ubuntu 20.04上的以下输出:

enter image description here

另请参见:wxPython: Putting a Background Image on a Panel


2
投票

已接受的答案已经说明了如何正确执行此操作,但是我还想解释一下您最初做错了什么:您不能只在WindowDC上绘制一次,并且希望完成任何操作。任何持久绘制都必须在PaintDC处理程序中的EVT_PAINT上完成,或者作为一种特殊的例外情况,必须在提供给EVT_BACKGROUND_ERASE处理程序的DC上完成。如果您设置了EVT_PAINT处理程序来调用原始set_tiling_background并从中使用PaintDC,它也会起作用。

事实上,在现代平台(GTK3,macOS)上,您既不能使用WindowDC也不能使用ClientDC,仅依靠它们是行不通的。

© www.soinside.com 2019 - 2024. All rights reserved.