Skip to main content

Gtk# on Mac using Visual Studio 2017

A preview version of Microsoft's Visual Studio 2017 got released for the OSX platform last March 15, 2017. Since that time, I've been using it to develop cross platform applications. Like many, I did not have the time to study Objective-C or Swift. Instead, I had to quickly learn C# on the job.

I consider C# to be an interesting choice for three reasons

  • It is supported on Mac and Linux platforms via the Mono framework
  • In theory, source code with little or no modification can be cross compiled on other platforms
  • Gtk is available on Windows/Linux/OSX
The last part clinched the decision the for me: creating user interfaces for the Mac via Xcode is too complex to tackle now. See: https://developer.xamarin.com/guides/mac/user-interface/working-with-windows/

User interfaces with Gtk, on the other hand, is quite straightforward. It behaves very much like Visual Basic; dragging and dropping widgets and attaching events (signals in Gtk parlance) for button clicks, mouse movement, etc. This does not make for an elegant way of programming. It encourages jumping right into code: Hack several pieces of it and hope the finished product is useful. And, if you're lucky, you get to refactor it and generally make it cleaner and more beautiful.

Shown below is the welcome screen of Visual Studio for Mac 2017 preview version.


... which should look familiar to anyone making his bread and butter on Visual Studio.

Inside, on the user interface designer, we have Gtk's assortment of widgets that can be dragged onto the empty canvas (MainWindow):


Then of course, the source code editor. Nothing surprising here.


One of the first issues I had to tackle was working with both Bitmap and Pixbuf formats. Graphics manipulation on the Windows platform almost always involves the former. The latter is used extensively in Gtk's framework. 

How to convert to/from both formats? After testing several diverse, elegant, and weird answers on stackoverflow.com and google.com, I've settled on the following:

public Bitmap ToBitmap(Pixbuf src)
{
     if (src == null
return null;

     var stream = new MemoryStream(src.SaveToBuffer("bmp"))
     {
          Position = 0
     };
     
     return new Bitmap(stream);
}

public Pixbuf ToPixbuf(Bitmap src)
{
     if (src == nullreturn null;
                
     using (MemoryStream stream = new MemoryStream())
     {
          src.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)
          stream.Position = 0;
          
          return new Pixbuf(stream);
     }
}

These two pieces of code solved a lot of issues especially when I began experimenting with different image processing libraries. Eventually, I'll be building a library for similar snippets of useful code and make it available on GitHub.

Here's a sample from my experiments with OpenCV (Open source Computer Vision library)



blob counting using OpenCV

Resources

Comments