2017-06-06 66 views
3

是否有人能夠幫助我將這種方法在ios中轉換爲mac版本?代碼是用C#在Xamarin翻譯CGContext生成圖像方法從ios到mac

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

回答

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或確保你的背景下DisposeCGImage,以避免內存泄漏

+0

的感謝!我想知道如果我想使用一個CGContext,而應該如何從那裏做一個NSImage或CGImage?看起來,Apple有一個內置的makeImage()方法,而xamarin沒有 – Xiangyu

+0

@Xiangyu Swift的'makeImage'是一個ObjC'CGBitmapContextCreateImage',只能通過位圖上下文獲得,而Xamarin的'ToImage'則是'CGBitmapContextCreateImage' – SushiHangover

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

希望這helps.-