Search code examples
macosxamarinnsimagemonomaccgpath

Rendering CGPath as a NSImage on Mac


I have a set of shapes which I generate usingCGPath. I want to save all those CGPath which I have generated on the disk. Basically I want to render these CGPath as NSImage, so that either I can save them on disk or atleast save their Base64 encoded string.

Here is an example of it done on iOS - Export CGPath as JPG or PNG

I am trying to do something similar on Mac. I am using MonoMac for this and would not mind any Objective-C answers either. I am not even looking for the code, just some hints would be enough.

I have a CGPath as an argument to the method and the method returns NSImage. This method would be called for all the CGPath being generated in another module.


Solution

  • I found the answer after googling and asking people

    It needs CGBitmapContext

    Create an instance of CGBitmapContext using IntPtr.Zero so that Quartz can allocate memory for you

    var context = new CGBitmapContext (IntPtr.Zero, width, height,
        8, 4 * column, CGColorSpace.CreateDeviceRGB (),
        CGImageAlphaInfo.PremultipliedFirst))
    

    then set the Stroke Color

    context.SetStrokeColor (new CGColor (0.5f, 0.5f, 0.5f));
    

    Set line width

    context.SetLineWidth (2f);
    

    Add CGPath to this context

    context.AddPath (cgpath);
    

    then stroke the path

    context.StrokePath ()
    

    Get the CGImage from the context and create a NSImage from it

    var cgimg = context.ToImage ();
    var nsImage = new NSImage (cgimg, new CGSize (cgimg.Width, cgimg.Height));