423. How to place a background image in GtkEventBox - Part 1 - tiled background image?

Problem

This is in response to Andreas' Post titled "Possible to add not tiled backgrounds".

Suppose you want to place some background image in a GtkEventBox as shown below:

How to place a background image in GtkEventBox - Part 1 - tiled background image?


Solution


Sample Code

Note: The following image file is required by the sample code below. Please save a copy of the image files and put them in the same directory where you store the sample code.

 ball_blue3a.png

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
17   
18   
19   
20   
21   
22   
25   
26   
28   
29   
30   
31   
32   
33   
34   
35   
36   
37   
<?php
$window = new GtkWindow();
$window->set_size_request(480, 240);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Place a background image in GtkEventBox\n".
"        Part 1 - tiled background image");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0);
$vbox->pack_start(new GtkLabel(), 0);

$eventbox = new GtkEventBox(); // note 1
$vbox->pack_start($eventbox);
$eventbox->add($vbox2 = new GtkVBox());
$vbox2->pack_start(new GtkLabel("this is an eventbox"));
$vbox2->pack_start(new GtkLabel("the blue ball is the bg image"));

// set background image
$pixbuf=GdkPixbuf::new_from_file("ball_blue3a.png"); // note 2
list($pixmap,$mask)=$pixbuf-> render_pixmap_and_mask(255); // note 3
$style = $eventbox->get_style(); // note 4
$style=$style->copy(); // note 5
$style->bg_pixmap[Gtk::STATE_NORMAL]=$pixmap; // note 6
$eventbox->set_style($style); //note 7

$window->show_all();
Gtk::main();
?>

Output

As shown above.
 

Explanation

  1. Create the eventbox.
  2. Load the background image. This works with all standard image file format such as .gif, .jpg or .png.
  3. Convert to pixmap.
  4. Get the GtkStyle corresponding to the eventbox.
  5. Make a copy of the style.
  6. Set the background image.
  7. Set the eventbox with the new style.

Note

  • The image used above is saved without transpency.
  • If you've tried placing a background image with transparency, you will find that using the technique described in this article doesn't work. The transparent areas will appear in black as shown below:
  • If you need to place a background image with transparency, use the method as described in the next article.

Related Links

Add comment


Security code
Refresh