U3D 三种实现截屏保存精彩瞬间方式

using UnityEngine;
using System.Collections;
using System;
using System.IO;
public class CaptrueCameraScript : MonoBehaviour
{
        public static string pic_fileName;
        public UITexture smallTex;
        /// <summary>
        /// 对相机截屏,并保存
        /// </summary>
        /// <returns>The camera.</returns>
        /// <param name="camera">Camera.</param>
        /// <param name="rect">Rect.</param>
        public Texture2D CaptrueCamera (Camera camera, Rect rect)
        {
                // 创建一个RenderTexture对象  
                RenderTexture rt = new RenderTexture ((int)rect.width, (int)rect.height, 0);  
                // 临时设置相关相机的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);
                string formatType = ".png";
                string formatTime = DateTime.Now.ToString ();
                formatTime = formatTime.Replace ('/', '-').Replace (' ', '-').Replace (':', '-').ToString ();
                // 最后将这些纹理数据,成一个png图片文件  
                byte[] bytes = screenShot.EncodeToPNG ();
                string filename = null;
                #if UNITY_ANDROID
                    filename = Application.persistentDataPath + "/" + formatTime + formatType;
        Debug.Log("android!");
                #elif UNITY_IPHONE
                    filename = Application.persistentDataPath + "/" + formatTime + formatType;
        Debug.Log("ios");
                #elif UNITY_EDITOR
                    filename = Application.dataPath + "/" + formatTime + formatType;
        Debug.Log("editor");
                #endif
                System.IO.File.WriteAllBytes (filename, bytes);  
                Debug.Log (string.Format ("截屏了一张照片: {0}", filename));  

                return screenShot;  
        }
        private IEnumerator ReadFileLoadTex ()
        {
                yield return 0;
                string path = null;
                #if UNITY_ANDROID
                    path=Application.persistentDataPath+"/"+pic_fileName;
                #elif UNITY_IPHONE
                    path=Application.persistentDataPath+"/"+pic_fileName;
                #elif UNITY_EDITOR
                    path=Application.dataPath+"/"+pic_fileName;
                #endif
                FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read);
                fs.Seek (0, SeekOrigin.Begin);
                //创建文件长度缓存
                byte[] bytes = new byte[fs.Length];
                //读取文件
                fs.Read (bytes, 0, (int)fs.Length);
                //释放文件读取流
                fs.Close ();
                fs.Dispose ();
                fs = null;

                //创建texture
                Texture2D tex = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);
                tex.LoadImage (bytes);
//      图片赋值
//              GameObject.Find ("UI Root/Texture").GetComponent<UITexture> ().mainTexture = tex;
//              GameObject.Find ("Canvas/RawImage").GetComponent<RawImage> ().texture = tex;
        }

}


第二个类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;

public class CaptureMgr : MonoBehaviour {


    //定义图片保存路径  
    private string mPath1;
    private string mPath2;
    private string mPath3;

    //相机  
    public Transform CameraTrans;
    string screenShotFolder = "screenShot";

   

    void Start()
    {
        Debug.Log(Application.persistentDataPath);
        //初始化路径  
        mPath1 = Application.persistentDataPath + "\\ScreenShot1.jpg";
        mPath2 = Application.persistentDataPath + "\\ScreenShot2.jpg";
        mPath3 = Application.persistentDataPath + "\\ScreenShot3.jpg";

        CreateFolder(screenShotFolder);
    }

    void CreateFolder(string folder)
    {
        string fullName = Application.persistentDataPath + "/" + folder + "/";
        try
        {
            bool flag = !Directory.Exists(fullName);
            if (flag)
            {
                Directory.CreateDirectory(fullName);
            }
        }
        catch (Exception ex2)
        {
            Debug.Log("create folder failure");
            return;
        }
    }

    //主方法,使用UGUI实现  
    void OnGUI()
    {
        if (GUILayout.Button("截图方式1", GUILayout.Height(30)))
        {
            CaptureByUnity(Application.persistentDataPath + "/" + screenShotFolder + "/"+Time.time+".jpg");
        }
        if (GUILayout.Button("截图方式2", GUILayout.Height(30)))
        {
            StartCoroutine(CaptureByRect(new Rect(0, 0, 1024, 768), Application.persistentDataPath + "/" + screenShotFolder + "/" + Time.time + ".jpg"));
        }
        if (GUILayout.Button("截图方式3", GUILayout.Height(30)))
        {
            //启用顶视图相机  
            CameraTrans.GetComponent<Camera>().enabled = true;
            //禁用主相机  
            //Camera.main.enabled = false;
            StartCoroutine(CaptureByCamera(CameraTrans.GetComponent<Camera>(), new Rect(0, 0, 1024, 768), Application.persistentDataPath + "/" + screenShotFolder + "/" + System.DateTime.Now.ToString() + ".jpg"));
        }
    }
    /// <summary>  
    /// 使用Application类下的CaptureScreenshot()方法实现截图  
    /// 优点:简单,可以快速地截取某一帧的画面、全屏截图  
    /// 缺点:不能针对摄像机截图,无法进行局部截图  
    /// </summary>  
    /// <param name="mFileName">M file name.</param>  
    private void CaptureByUnity(string mFileName)
    {
        Application.CaptureScreenshot(mFileName, 0);
    }

    /// <summary>  
    /// 根据一个Rect类型来截取指定范围的屏幕  
    /// 左下角为(0,0)  
    /// </summary>  
    /// <param name="mRect">M rect.</param>  
    /// <param name="mFileName">M file name.</param>  
    private IEnumerator CaptureByRect(Rect mRect, string mFileName)
    {
        //等待渲染线程结束  
        yield return new WaitForEndOfFrame();
        //初始化Texture2D  
        Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.RGB24, false);
        //读取屏幕像素信息并存储为纹理数据  
        mTexture.ReadPixels(mRect, 0, 0);
        //应用  
        mTexture.Apply();


        //将图片信息编码为字节信息  
        byte[] bytes = mTexture.EncodeToJPG();
        //保存  
        System.IO.File.WriteAllBytes(mFileName, bytes);

        //如果需要可以返回截图  
        //return mTexture;  
    }

    private IEnumerator CaptureByCamera(Camera mCamera, Rect mRect, string mFileName)
    {
        //等待渲染线程结束  
        yield return new WaitForEndOfFrame();

        //初始化RenderTexture  
        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.RGB24, false);
        //读取屏幕像素信息并存储为纹理数据  
        mTexture.ReadPixels(mRect, 0, 0);
        //应用  
        mTexture.Apply();

        //释放相机,销毁渲染贴图  
        mCamera.targetTexture = null;
        RenderTexture.active = null;
        GameObject.Destroy(mRender);

        //将图片信息编码为字节信息  
        byte[] bytes = mTexture.EncodeToJPG();
        //保存  
        System.IO.File.WriteAllBytes(mFileName, bytes);
       
        //如果需要可以返回截图  
        //return mTexture;  
    }
}



猜你喜欢

转载自blog.csdn.net/lizhenxiqnmlgb/article/details/80439855
今日推荐