save, restore and *_preserve



Hi!

I'm using a Gtk::DrawingArea to do some a special profiling drawing tool.
At some point, I want to draw a box, fill it with a color, stroke it in black and write a text on it (and not drawing out of the box). I succeeded in a way, but I'm not sure it's the perfect way of doing it.
Since the drawings in this DrawingArea will be pretty intensive, I'd like to have some advice from you because I'm a bit lost with what save, restore and *_preserve methods do...

Here the (simplified) code of the drawing:

    // In the on_draw() method.
    // cr is a Cairo::RefPtr<Cairo::Context> const&.
    // For each box I've got to draw.

    // Set the rectangle bounds.
    cr->rectangle(rectX, rectY, rectWidth, rectHeight);
   
    // Save it, fill, preserve and restore.
    cr->save();
    cr->set_source_rgb(1.0, 0.8, 0.5);
    cr->fill_preserve();
    cr->restore();

    // Save it again, stroke, preserve and restore.
    cr->save();
    cr->set_source_rgb(0.0, 0.0, 0.0);
    cr->set_line_width(1.0);
    cr->stroke_preserve();
    cr->restore();

    // Initialize pango font.
    Pango::FontDescription font;
    font.set_family("DejaVu Sans");
    font.set_size(12 * PANGO_SCALE);
    font.set_stretch(Pango::STRETCH_CONDENSED);

    // Initialize pango layout.
    Glib::RefPtr<Pango::Layout> layout = create_pango_layout(text);
    layout->set_font_description(font);

    // Get the text dimensions.
    int textWidth;
    int textHeight;
    layout->get_pixel_size(textWidth, textHeight);

    // Position the text in the middle.
    // Save, clip, set color, move to the middle, draw text, reset clip, restore.
    cr->save();
    cr->clip();
    cr->set_source_rgb(0.0, 0.0, 0.0);
    cr->move_to(rectX + (rectWidth - textWidth) / 2, rectY + (rectHeight - textHeight) / 2);
    layout->show_in_cairo_context(cr);
    cr->reset_clip();
    cr->restore();

Trust me, if I remove one save/restore or one preserve, the draw is becoming pretty f*cked up.
Maybe a first thing would be to cache the font.
Do you have other ideas, GTKMM gurus? ;)

Cheers,
Creak


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]