unity 截屏并保存

 public override void OnPointerDown(Vector3 position)
    {
        base.OnPointerDown(position);
        toolBox.SetActive(false);
        observeCamera.clearFlags = CameraClearFlags.SolidColor;//清除标记
        string str = System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute + ":" + System.DateTime.Now.Second;
        imgPath += "/" + System.DateTime.Now.Year + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Day + " " + str + ".png";
        StartCoroutine(CaptureByCamera(observeCamera, new Rect(0, 0, Screen.width, Screen.height), imgPath));

    }

    /// 
    /// 截屏保存图片
    /// 
    /// 渲染相机
    /// 截屏区域大小
    /// 保存路径
    /// 
    private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string filePath)
    {
        yield return new WaitForEndOfFrame();
        //设置RenderTexture
        mCamera.gameObject.SetActive(true);
        RenderTexture mRender = new RenderTexture((int)mRect.width, (int)mRect.height, 0);
        mCamera.targetTexture = mRender;
        mCamera.Render();
        RenderTexture.active = mRender;
        Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.ARGB32, false);
        //读取屏幕像素
        mTexture.ReadPixels(mRect, 0, 0);
        mTexture.Apply();
        mCamera.targetTexture = null;
        RenderTexture.active = null;
        Destroy(mRender);
        //转换成字节保存
        byte[] bytes = mTexture.EncodeToPNG();
        File.WriteAllBytes(filePath, bytes);
        toolBox.SetActive(true);
        mCamera.enabled = false;
        mCamera.clearFlags = CameraClearFlags.Skybox;
    }

你可能感兴趣的:(unity 截屏并保存)