Unity 截图工具

从网上找的截图脚本,使用很方便在这里记录一下

using System.IO;
using UnityEditor;
using UnityEngine;

public class ScreenShotWindow : EditorWindow
{
    private Camera m_Camera;
    private string filePath;
    private bool m_IsEnableAlpha = false;
    private CameraClearFlags m_CameraClearFlags;

    [MenuItem("Tools/屏幕截图")]
    private static void Init()
    {
        ScreenShotWindow window = GetWindowWithRect<ScreenShotWindow>(new Rect(0, 0, 300, 150));
        window.titleContent = new GUIContent("屏幕截图");
        window.Show();
    }

    private void OnGUI()
    {
        EditorGUILayout.Space();
        m_Camera = EditorGUILayout.ObjectField("选择摄像机", m_Camera, typeof(Camera), true) as Camera;

        if (GUILayout.Button("保存位置"))
        {
            filePath = EditorUtility.OpenFolderPanel("", "", "");
        }

        m_IsEnableAlpha = EditorGUILayout.Toggle("是否开启透明通道", m_IsEnableAlpha);
        EditorGUILayout.Space();
        if (GUILayout.Button("截图"))
        {
            TakeShot();
        }
        EditorGUILayout.Space();
        if (GUILayout.Button("打开导出文件夹"))
        {
            if (string.IsNullOrEmpty(filePath))
            {
                Debug.LogError("<color=red>" + "没有选择截图保存位置" + "</color>");
                return;
            }
            Application.OpenURL("file://" + filePath);
        }
    }

    private void TakeShot()
    {
        if (m_Camera == null)
        {
            Debug.LogError("<color=red>" + "没有选择摄像机" + "</color>");
            return;
        }

        if (string.IsNullOrEmpty(filePath))
        {
            Debug.LogError("<color=red>" + "没有选择截图保存位置" + "</color>");
            return;
        }

        m_CameraClearFlags = m_Camera.clearFlags;
        if (m_IsEnableAlpha)
        {
            m_Camera.clearFlags = CameraClearFlags.Depth;
        }

        int resolutionX = (int)Handles.GetMainGameViewSize().x;
        int resolutionY = (int)Handles.GetMainGameViewSize().y;
        RenderTexture rt = new RenderTexture(resolutionX, resolutionY, 24);
        m_Camera.targetTexture = rt;
        Texture2D screenShot = new Texture2D(resolutionX, resolutionY, TextureFormat.ARGB32, false);
        m_Camera.Render();
        RenderTexture.active = rt;
        screenShot.ReadPixels(new Rect(0, 0, resolutionX, resolutionY), 0, 0);
        m_Camera.targetTexture = null;
        RenderTexture.active = null;
        m_Camera.clearFlags = m_CameraClearFlags;
        //Destroy(rt);
        byte[] bytes = screenShot.EncodeToPNG();
        string fileName = filePath + "/" + "a" + ".png";
        File.WriteAllBytes(fileName, bytes);
        Debug.Log("截图成功");
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值