Unity 截屏工具代码

文章描述了一个Unity编辑器插件,提供了使用不同分辨率和透明背景的截图功能,通过自定义快捷键实现快速截图并保存到指定路径。
摘要由CSDN通过智能技术生成
using System;
using System.IO;
using UnityEditor;
using UnityEditor.ShortcutManagement;
using UnityEngine;

/// <summary>
/// 截屏工具类
/// </summary>
public static class ScreenshotUtilities
{
    [Shortcut("MT_Tools/Take Screenshot 1x", KeyCode.Alpha1, ShortcutModifiers.Alt)]
    [MenuItem("MT_Tools/Take Screenshot/Native Resolution &Alpha1")] //快捷键Alt+Alpha1
    private static void CaptureScreenshot1X()
    {
        CaptureScreenshot(GetScreenshotPath(), 1);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    [Shortcut("MT_Tools/Take Screenshot 1x Alpha", KeyCode.Alpha1, ShortcutModifiers.Shift)]
    [MenuItem("MT_Tools/Take Screenshot/Native Resolution (Transparent Background) #Alpha1")]
    private static void CaptureScreenshot1XAlphaComposite()
    {
        CaptureScreenshot(GetScreenshotPath(), 1, true);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    [Shortcut("MT_Tools/Take Screenshot 2x", KeyCode.Alpha2, ShortcutModifiers.Alt)]
    [MenuItem("MT_Tools/Take Screenshot/2x Resolution &Alpha2")]
    private static void CaptureScreenshot2X()
    {
        CaptureScreenshot(GetScreenshotPath(), 2);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    [Shortcut("MT_Tools/Take Screenshot 2x Alpha", KeyCode.Alpha2, ShortcutModifiers.Shift)]
    [MenuItem("MT_Tools/Take Screenshot/2x Resolution (Transparent Background) #Alpha2")]
    private static void CaptureScreenshot2XAlphaComposite()
    {
        CaptureScreenshot(GetScreenshotPath(), 2, true);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    [Shortcut("MT_Tools/Take Screenshot 4x", KeyCode.Alpha4, ShortcutModifiers.Alt)]
    [MenuItem("MT_Tools/Take Screenshot/4x Resolution &Alpha4")]
    private static void CaptureScreenshot4X()
    {
        CaptureScreenshot(GetScreenshotPath(), 4);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    [Shortcut("MT_Tools/Take Screenshot 4x Alpha", KeyCode.Alpha4, ShortcutModifiers.Shift)]
    [MenuItem("MT_Tools/Take Screenshot/4x Resolution (Transparent Background) #Alpha4")]
    private static void CaptureScreenshot4XAlphaComposite()
    {
        CaptureScreenshot(GetScreenshotPath(), 4, true);
        EditorUtility.RevealInFinder(GetScreenshotDirectory());
    }

    /// <summary>
    /// 使用当前主摄像头的清晰颜色捕获屏幕截图。
    /// </summary>
    /// <param name="path">要将屏幕截图保存到的路径。</param>
    /// <param name="superSize">分辨率倍率</param>
    /// <param name="transparentClearColor">如果捕获的屏幕截图应具有透明的透明颜色,则为 True。可用于屏幕截图叠加。</param>
    /// <param name="camera">要从中截取屏幕截图的可选摄像头。</param>
    /// <returns>成功捕获屏幕截图时为 true,否则为 false。</returns>
    private static bool CaptureScreenshot(string path, int superSize = 1, bool transparentClearColor = false,
        Camera camera = null)
    {
        if (string.IsNullOrEmpty(path) || superSize <= 0)
        {
            return false;
        }

        // 确保有一个有效的摄像机来渲染。
        if (camera == null)
        {
            camera = Camera.main;

            if (camera == null)
            {
                camera = GameObject.FindObjectOfType<Camera>();

                if (camera == null)
                {
                    Debug.LogError("Failed to find a any cameras to capture a screenshot from.");

                    return false;
                }
                else
                {
                    Debug.LogWarning(
                        $"Capturing screenshot from a camera named \"{camera.name}\" because there is no camera tagged \"MainCamera\".");
                }
            }
        }

        // 创建一个克隆摄像机
        var renderCamera = new GameObject().AddComponent<Camera>();
        renderCamera.CopyFrom(camera);
        renderCamera.orthographic = camera.orthographic;
        renderCamera.transform.position = camera.transform.position;
        renderCamera.transform.rotation = camera.transform.rotation;
        renderCamera.clearFlags = transparentClearColor ? CameraClearFlags.Color : camera.clearFlags;
        renderCamera.backgroundColor = transparentClearColor
            ? new Color(0.0f, 0.0f, 0.0f, 0.0f)
            : new Color(camera.backgroundColor.r, camera.backgroundColor.g, camera.backgroundColor.b, 1.0f);

        // 为要渲染到的摄像机克隆创建渲染纹理。
        var width = Screen.width * superSize;
        var height = Screen.height * superSize;
        var renderTexture = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
        renderTexture.antiAliasing = 8;
        renderCamera.targetTexture = renderTexture;

        // 从摄像机克隆渲染。
        renderCamera.Render();

        // 从摄像机复制渲染并将其保存到磁盘。
        var outputTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
        RenderTexture previousRenderTexture = RenderTexture.active;
        RenderTexture.active = renderTexture;
        outputTexture.ReadPixels(new Rect(0.0f, 0.0f, width, height), 0, 0);
        outputTexture.Apply();
        RenderTexture.active = previousRenderTexture;

        try
        {
            File.WriteAllBytes(path, outputTexture.EncodeToPNG());
        }
        catch (Exception e)
        {
            Debug.LogException(e);

            return false;
        }
        finally
        {
            UnityEngine.Object.DestroyImmediate(outputTexture);
            UnityEngine.Object.DestroyImmediate(renderCamera.gameObject);
            UnityEngine.Object.DestroyImmediate(renderTexture);
        }

        Debug.LogFormat("Screenshot captured to: {0}", path);

        return true;
    }

    /// <summary>
    /// 获取保存屏幕截图的目录。
    /// </summary>
    /// <returns>用于保存屏幕截图的目录。</returns>
    private static string GetScreenshotDirectory()
    {
        return Application.temporaryCachePath;
    }

    /// <summary>
    /// 获取具有基于日期和时间的文件名的唯一屏幕截图路径。
    /// </summary>
    /// <returns>唯一的屏幕截图路径。</returns>
    private static string GetScreenshotPath()
    {
        return Path.Combine(GetScreenshotDirectory(),
            string.Format("Screenshot_{0:yyyy-MM-dd_hh-mm-ss-tt}_{1}.png", DateTime.Now, GUID.Generate()));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值