3

Is anyone able to help me translate this method in ios to mac version? Code is written in C# in Xamarin

public static UIImage GetImageFromColor(UIColor color, float borderWidth = 1.0f)
    {
        var rect = new CGRect(0.0f, 0.0f, borderWidth, borderWidth);
        UIGraphics.BeginImageContext(rect.Size);
        var context = UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);
        context.FillRect(rect);

        var image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return image.CreateResizableImage(new UIEdgeInsets(1.0f, 1.0f, 1.0f, 1.0f));
    }
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
Xiangyu
  • 37
  • 6

2 Answers2

1

UIGraphics.BeginImageContext translates to a CGBitmapContext (or CGContext depending upon what you need).

So to fill a CGBitmapContext with a color:

var size = new CGSize(width, height);
var rect = new CGRect(new CGPoint(), size);

NSImage image;
using (var context = new CGBitmapContext(IntPtr.Zero, width, height, 8, width * 4, NSColorSpace.GenericRGBColorSpace.ColorSpace, CGImageAlphaInfo.PremultipliedFirst))
{
    context.SetFillColor(NSColor.Red.CGColor);
    context.FillRect(rect);
    using (var cgImage = context.ToImage())
    {
        image = new NSImage(cgImage, size);
    }
}

Note: You should use using or make sure that you Dispose of the context and CGImage to avoid a memory leak

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • thanks! I am wondering if I want to use a CGContext instead, how should I make a NSImage or CGImage from that? It seems that Apple has a built in makeImage() method while xamarin doesn't have – Xiangyu Jun 07 '17 at 16:04
  • @Xiangyu The Swift `makeImage` is an ObjC `CGBitmapContextCreateImage` and that is only available via a bitmap context and Xamarin's `ToImage` is the translation of `CGBitmapContextCreateImage` – SushiHangover Jun 07 '17 at 16:27
0

This is not a translation from the code you posted but it does exactly the same job:

public static NSImage GetImageFromColor (NSColor color, float borderWidth = 1.0f)
{
    var image = new NSImage (new CGSize (borderWidth, borderWidth));
    image.LockFocus ();
    color.DrawSwatchInRect (new CGRect (new CGPoint (0, 0), image.Size));
    image.UnlockFocus ();

    return image;
}

Hope this helps.-

pinedax
  • 9,246
  • 2
  • 23
  • 30