使用ScreenCapture.CaptureScreenshot捕获并保存屏幕截图

我一直试图截取屏幕截图,然后立即使用它来显示某种预览,有时它会起作用,有时却不起作用,我目前没有工作,我没有统一这台计算机所以我会尝试在运行中重新创建它(这里可能存在一些语法错误)

public GameObject screenshotPreview; public void TakeScreenshot () { string imageName = "screenshot.png"; // Take the screenshot ScreenCapture.CaptureScreenshot (imageName); // Read the data from the file byte[] data = File.ReadAllBytes(Application.persistentDataPath + "/" + imageName); // Create the texture Texture2D screenshotTexture = new Texture2D(Screen.width, Screen.height); // Load the image screenshotTexture.LoadImage(data); // Create a sprite Sprite screenshotSprite = Sprite.Create (screenshotTexture, new Rect(0, 0, Screen.width, Screen.height), new Vector2(0.5f, 0.5f) ); // Set the sprite to the screenshotPreview screenshotPreview.GetComponent ().sprite = screenshotSprite; } 

据我所知,ScreenCapture.CaptureScreenshot不是异步的,所以图像应该在我尝试加载数据之前写入,但问题就像我之前说的那样,有些时候它不起作用并加载带有红色问号的8×8纹理,显然是纹理无法加载,但文件应该已经存在,所以我无法理解为什么它没有正确加载。

我尝试过的另一件事(令人厌恶,但我已经厌倦了这个并且用完了想法)就是放入更新方法等待一段时间,然后执行代码来加载数据并创建纹理,精灵并显示它,但即便如此,它失败了一些时间,比之前更少但它仍然失败,这使我相信,即使文件创建它还没有完成beign写,有没有人知道解决方法吗? 任何建议表示赞赏。

作为额外信息,该项目正在iOS设备中运行。

已知ScreenCapture.CaptureScreenshot函数存在许多问题。 这是另一个。

以下是其文档的引用:

在Android上,此function立即返回。 生成的屏幕截图稍后可用。

iOS行为没有记录,但我们可以假设iOS上的行为是相同的。 在尝试读取/加载屏幕截图之前,请等待几帧。

 public IEnumerator TakeScreenshot() { string imageName = "screenshot.png"; // Take the screenshot ScreenCapture.CaptureScreenshot(imageName); //Wait for 4 frames for (int i = 0; i < 5; i++) { yield return null; } // Read the data from the file byte[] data = File.ReadAllBytes(Application.persistentDataPath + "/" + imageName); // Create the texture Texture2D screenshotTexture = new Texture2D(Screen.width, Screen.height); // Load the image screenshotTexture.LoadImage(data); // Create a sprite Sprite screenshotSprite = Sprite.Create(screenshotTexture, new Rect(0, 0, Screen.width, Screen.height), new Vector2(0.5f, 0.5f)); // Set the sprite to the screenshotPreview screenshotPreview.GetComponent().sprite = screenshotSprite; } 

请注意,您必须使用StartCoroutine(TakeScreenshot()); 调用此function。


如果这不起作用,请不要使用此function。 这是在Unity中获取和保存屏幕截图的另一种方法:

 IEnumerator captureScreenshot() { yield return new WaitForEndOfFrame(); string path = Application.persistentDataPath + "Screenshots/" + "_" + screenshotCount + "_" + Screen.width + "X" + Screen.height + "" + ".png"; Texture2D screenImage = new Texture2D(Screen.width, Screen.height); //Get Image from screen screenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); screenImage.Apply(); //Convert to png byte[] imageBytes = screenImage.EncodeToPNG(); //Save image to file System.IO.File.WriteAllBytes(path, imageBytes); } 

我在文档中没有看到任何说不是异步的内容。 事实上,对于Android(如果我正确地阅读它),它明确地说它是异步的。

也就是说,在找不到文件的时候我会尝试拖延。 把它扔进协程,而(!file.found)收益? 您还可以尝试在其中引入一些调试检查,以查看文件出现之前需要多长时间(秒或帧)(假设它出现)。

Interesting Posts