Unity3d之如何截屏


Unity3d中有時有截屏的需求,那如何截屏呢,代碼如下:

    /// <summary>
    /// 截屏
    /// </summary>
    /// <param name="camera">截屏的攝像機</param>
    /// <param name="rect">圖片大小</param>
    /// <returns>屏幕快照</returns>
    Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        RenderTexture originRT = camera.targetTexture;      // 臨時把camera中的targetTexture替換掉
        camera.targetTexture = rt;
        camera.RenderDontRestore();                         // 手動渲染
        camera.targetTexture = originRT;

        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height);
        screenShot.ReadPixels(rect, 0, 0);                  // 讀取的是 RenderTexture.active 中的像素
        screenShot.Apply();
        GameObject.Destroy(rt);
        RenderTexture.active = null;

        return screenShot;
    }

 如何保存 Texture2D 圖片:

    static void SaveImage(Texture2D image, string path)
    {
        byte[] buffer = image.EncodeToPNG();
        File.WriteAllBytes(path, buffer);
    }

 

轉載請注明出處:http://www.cnblogs.com/jietian331/p/6899725.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM