Exemple #1
0
        private static IEnumerator TakeScreenshot()
        {
            DebugScreen instance = FindObjectOfType <DebugScreen>();

            if (instance != null)
            {
                yield return(null); // prevent error in DebugScreen

                instance.Hide();
                yield return(null); // make sure the debug screen is hidden when we take the screenshot
            }

            yield return(new WaitForEndOfFrame()); // necessary so everything is rendered as it should

            try
            {
                // Doesn't work as of KSP 1.11 / DX11 : ground texture are rendered as transparent for some reason
                // byte[] shotPNG = ScreenCapture.CaptureScreenshotAsTexture(1).EncodeToPNG();

                // Create a texture the size of the screen, RGB24 format
                int       width  = Screen.width;
                int       height = Screen.height;
                Texture2D tex    = new Texture2D(width, height, TextureFormat.RGB24, false);

                // Read screen contents into the texture
                tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
                tex.Apply();
                byte[] shotPNG = tex.EncodeToPNG();


                string pngFileName = null;

                using (ZipArchive archive = ZipFile.Open(lastReportPath, ZipArchiveMode.Update))
                {
                    using (Stream memoryStream = new MemoryStream(shotPNG))
                    {
                        pngFileName = "Screenshot_" + DateTime.Now.ToString(@"yyyy-MM-dd_HHmmss") + ".png";
                        ZipArchiveEntry zipArchiveEntry =
                            archive.CreateEntry(pngFileName, System.IO.Compression.CompressionLevel.Optimal);
                        using (Stream entryStream = zipArchiveEntry.Open())
                        {
                            memoryStream.CopyTo(entryStream);
                        }
                    }
                }

                ScreenMessages.PostScreenMessage(
                    $"Screenshot :\n<color=#FF8000>{pngFileName}</color>\n added to report :\n<color=#FF8000>{Path.GetFileName(lastReportPath)}</color>",
                    5f, ScreenMessageStyle.UPPER_CENTER, true);
                Lib.Log($"Screenshot {pngFileName} added to report {Path.GetFileName(lastReportPath)}");
            }
            catch (Exception e)
            {
                ScreenMessages.PostScreenMessage($"Error creating a screenshot", 5f, ScreenMessageStyle.UPPER_CENTER, Color.red);
                Lib.Log($"Error creating screenshot\n{e}", Lib.LogLevel.Warning);
            }

            if (instance != null)
            {
                yield return(null);

                instance.Show();
            }
        }