GTK Sharp 3 Adventures

Lessons learnt over time

Posted by Chris Lapa on August 18, 2017

GTK Sharp 3 is a good UI toolkit however as usual when you start to get deep into these toolkits you often discover lots of not so obvious traps.

Cairo Coordinate Modes

Cairo has two coordinate modes, Device and User.

  • Device mode coordinates are relative to the display: 0,0 = top left corner of the display.
  • User mode coordinates are relative to the widget: 0,0 = top left corner of the widget.

Basic overriding of OnDrawn() method:

We have to call ShouldDrawWindow() and TransformToWindow() to transform the coordinate space from widget relative to display relative. Without this transform the widget won’t draw correctly when it is placed in a ViewPort.

protected override bool OnDrawn (Cairo.Context context)
{
	if (Gtk.CairoHelper.ShouldDrawWindow (context, Window))
	{
		context.Save ();
		Gtk.CairoHelper.TransformToWindow (context, this, Window);

		// Draw stuff here!

		context.Restore ();
	}
}

Propagating Draw to children widgets

foreach (Widget w in AllChildren)
{
	context.Save ();
	PropagateDraw (w, context);
	context.Restore ();
}

Adding CSS to a Widget at Run Time

public static CssProvider AddCss(Widget widget, string css)
{
	CssProvider provider = new CssProvider ();
	provider.LoadFromData (css);
	widget.StyleContext.AddProvider (provider, 600);
	return provider;
}

Buttons Inherits Container

When you set the Image or Label property on a Button instance, you are either adding a Image or a Label to the container. This means if you wanted to use Pango Markup on a Buttons text, you need to call Add() on the Button instance with a new Label. For example:

Label l = new Label();
l.UseMarkup = true;
l.Text = "<span foreground="blue" size="x-large">Blue text</span> is <i>cool</i>!""

Button b = new Button();
b.Add(l);

comments powered by Disqus