2017-08-16 100 views
3

我试图抓住屏幕截图并使用Xamarin和C#在Mac上将其保存在磁盘上。我写了下面的代码:Xamarin - 如何获取截图并使用xamarin mac将其保存在磁盘上?

public static void TakeScreenshotAndSaveToDisk(string path) 
    { 
     var fullScreenBounds = NSScreen.MainScreen.Frame; 
     IntPtr ptr = CGWindowListCreateImage(fullScreenBounds, CGWindowListOption.OnScreenAboveWindow, 0, CGWindowImageOption.Default); 
     var cgImage = new CGImage(ptr); 
     var fileURL = new NSUrl(path, false); 
     var imageDestination = CGImageDestination.Create(new CGDataConsumer(fileURL), UTType.PNG, 1); 
     imageDestination.AddImage(cgImage); 
     imageDestination.Close(); 
     imageDestination.Dispose(); 
     fileURL.Dispose(); 
     cgImage.Dispose(); 
    } 

该方法执行并且文件出现在正确的位置。如果我尝试打开它,它会显示为空白。如果我点击文件上的“获取信息”,它将不会显示预览。 关闭我的应用后,图像可以打开,“获取信息”显示预览。

我在这里做错了什么?在我看来,即使我在对象上调用Dispose(),资源也不会被释放。

谢谢。

回答

1

CGImageDestination.Create方法有3个不同的签名,如果你使用接受NSUrl而不是CGDataConsumer的方法,你应该是好的。

var imageDestination = CGImageDestination.Create(fileURL, UTType.PNG, 1); 

有了这一个你不需要创建CGDataConsumer但如果你真的想/需要

var dataConsumer = new CGDataConsumer(fileURL); 
var imageDestination = CGImageDestination.Create(dataConsumer, UTType.PNG, 1); 
imageDestination.AddImage(cgImage); 
imageDestination.Close(); 
dataConsumer.Dispose(); 

只要确保处置情况下,一旦你已经保存的文件。

随着using方法:

using (var dataConsumer = new CGDataConsumer(fileURL)) 
{ 
    var imageDestination = CGImageDestination.Create(dataConsumer, UTType.PNG, 1); 
    imageDestination.AddImage(cgImage); 
    imageDestination.Close(); 
} 

注意:为CGImageDestination你不需要手动配置,该Close方法也将部署(基于文档)的对象。

公共布尔关闭()

写入图像到目的地并配置对象。

希望这helps.-

+0

感谢Apineda。在CGDataConsumer对象上调用dispose是个窍门。 – BVintila