Unity两种截图方法

前言

Unity开发过程中可能会有在程序内截图的需求,下面给出两种方法

一.Unity自带截图

在这里插入图片描述
Unity自己封装好的,自己保存一下就好了

二.指定摄像机及截图大小进行截图

下面展示代码片

 public static Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        // 建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 1);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        camera.targetTexture = rt;
        camera.Render();

        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;  
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();

        // 获取系统时间
        System.DateTime now = new System.DateTime();
        now = System.DateTime.Now;
        string picName = string.Format("image{0}{1}{2}{3}{4}{5}.png", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);


        string filename =

#if UNITY_EDITOR || UNITY_STANDALONE
            Application.streamingAssetsPath + "/" + picName;
#elif UNITY_ANDROID
		"/sdcard/DCIM/Camera/"+picName;
#endif


        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();
#endif

        return screenShot;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42066580/article/details/106670944