Xamarin - 如何使用 xamarin mac 获取屏幕截图并将其保存在磁盘上?

BVi*_*ila 5 c# macos screenshot xamarin xamarin.mac

我正在尝试在 Mac 上使用 Xamarin 和 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢。

pin*_*dax 3

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

var imageDestination = CGImageDestination.Create(fileURL, UTType.PNG, 1);
Run Code Online (Sandbox Code Playgroud)

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

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

只需确保在保存文件后处置该实例即可。

通过该using方法:

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

注意:如果CGImageDestination您不需要手动处置,该Close方法还将处置该对象(基于文档)。

公共布尔关闭 ()

将图像写入目的地并处理对象。

希望这可以帮助。-