是否有人能够帮助我将此方法在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));
}
答案 0 :(得分:1)
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
以避免内存泄漏
答案 1 :(得分:0)
这不是您发布的代码的翻译,但它的工作完全相同:
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;
}
希望这会有所帮助.-