将CGContext生成图像方法从iOS翻译到Mac



有人能帮我在ios中将此方法翻译成Mac版本吗?代码是用 C# 在 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));
}

UIGraphics.BeginImageContext转换为CGBitmapContext(或CGContext,具体取决于您的需要)。

因此,要用颜色填充CGBitmapContext

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);
}
}

注意:您应该使用using或确保Dispose上下文和CGImage以避免内存泄漏

这不是您发布的代码的翻译,但它执行完全相同的工作:

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;
}

希望这有帮助.-

最新更新