[英]Xamarin - How to get a screenshot and save it on disk using xamarin mac?
我正在尝试抓取屏幕截图并使用Xamarin和Mac上的C#将其保存在磁盘上。 我写了下面的代码:
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(),资源也不会被释放。
谢谢。
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
方法也将处置该对象(基于文档)。
public Boolean Close()
将图像写入目标并处理该对象。
希望这可以帮助。-
我可能会迟到,但刚刚使用Xamarin.Mac实现了这个Swift算法 ,并且也可以在无头模式下使用:
https://gist.github.com/MarcosCobena/b4768bacc1a112a4f38a9d11a19f1251
它依赖于“新”CoreGraphics绑定(一些已经存在于Xamarin.Mac中,但内部或私有)来检测显示并枚举它们。 最后,每个显示屏需要一个屏幕截图,将其保存为给定路径中的PNG。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.