Unity 截图分享实现

        public static IEnumerator CaptureScreenshot(Action callback)
        {
            yield return new WaitForEndOfFrame();//在当前帧绘制完后才截屏

            Rect rect = new Rect(0, 0, Screen.width, Screen.height);
            RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 24);
            Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);

            foreach (var camera in Camera.allCameras)
            {
                if(camera.isActiveAndEnabled)
                {
                    camera.targetTexture = rt;
                    camera.Render();
                    camera.targetTexture = null;
                }
            }

            RenderTexture prevActiveTex = RenderTexture.active;
            RenderTexture.active = rt;
            screenShot.ReadPixels(rect, 0, 0);
            screenShot.Apply();
            RenderTexture.active = prevActiveTex;

            byte[] bytes = screenShot.EncodeToJPG();
            string filePath = Application.persistentDataPath + Path.AltDirectorySeparatorChar + "y110share.jpg";
            File.WriteAllBytes(filePath, bytes);
            //callback?.invoke();
            if (callback != null)
            {
                callback.Invoke(filePath);
            }
            Destroy(screenShot);
            Destroy(rt);
            yield return null;
        }

 

你可能感兴趣的:(Unity3D)