【Unity3D日常开发】(二十二)Unity3D进行截图

2021-10-25 10:29:56 浏览数 (1)

一、前言

来看一下怎么截图的吧

二、效果

三、代码

代码语言:javascript复制
using UnityEngine;

public class Screenshot : MonoBehaviour
{
    //截图相机
    Camera capCamera;
    //保存图片
    Texture2D screenShot;

    void Start()
    {
        capCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
    }

    void OnGUI()
    {
        if (GUILayout.Button("Show"))
        {
            CaptureCamera();
        }
    }

    void CaptureCamera()
    {
        Rect rect = new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f);
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        capCamera.targetTexture = rt;
        capCamera.Render();
        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        //从RenderTexture.active中读取像素
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        capCamera.targetTexture = null;
        //避免重复添加的错误
        RenderTexture.active = null; 

        //销毁这个对象
        Destroy(rt);

        //保存图片
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.streamingAssetsPath   "/2.png";
        System.IO.File.WriteAllBytes(filename, bytes);
    }
}

0 人点赞