Taking a Screenshot

From Kudan AR Engine
Jump to: navigation, search

If you wish to capture the whole screen, then you can simply use the built-in screen capturing capabilities of the device you are using. If, however, you wish to capture the camera feed without the UI, for example, and save the image, you will need to do something slightly different.

For this example, we will be loading up the Kudan Sample scene and modifying the SampleApp script. First, declare a RawImage variable:

        public RawImage image;

Then add a Coroutine called TakeScreenshot, giving it parameters for a RawImage, Rectangle, File Name and Size Ratio.

 IEnumerator TakeScreenshot(RawImage image, Rect rect, string fileName, float ratio)
     // Wait for the end of the frame to avoid any rendering artifacts
     yield return new WaitForEndOfFrame();
     // Get the camera from which the screenshot will be grabbed
     Camera camera = Camera.main;
     // Apply the ratio
     rect.height *= ratio;
     rect.width  *= ratio;
     //Set the target texture render  
     // Create a a new Texture2D that is the same size as the camera view
     Texture2D texture = new Texture2D((int)(camera.pixelWidth), (int)(camera.pixelHeight));	
     // Read the pixels of the screen and apply them to the texture
     texture.ReadPixels(rect, 0, 0);
     // Encode To PNG
     byte[] bytes = texture.EncodeToPNG();	
     //Save to 
     System.IO.File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, bytes);
     // Apply texture to a UI element for testing purposes
     image.texture = texture;

Add the above code as a new Coroutine in the SampleApp script. Also add:

 public void screenshot()
     Rect rect = new Rect(0, 0, Screen.width, Screen.height);
     string fileName = DateTime.Now.Ticks + ".jpg";
     StartCoroutine(TakeScreenshot(image, rect, filename, 1));

As a new function. This is the function we will call when pressing a button.

Add a new button and a RawImage to the UI, making sure to reference the RawImage in the modified script and add the screenshot() function to the button.

With that set up, it should now be a matter of building & running the app, pressing the button and seeing the screenshot appear on the RawImage object, without any UI being displayed on it. If all has gone well, the image should also be saved in the persistent data path of the device.