将 CGContext 生成图像的方法从 ios 翻译成 mac

translate CGContext generating image method from ios to mac

有人能帮我把ios中的这个方法翻译成mac版本吗?代码是在 Xamarin

中用 C# 编写的
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));
    }

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

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

希望对您有所帮助。-

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 以避免内存泄漏