unity 截图并且展现在UI中

发布于:2025-03-30 ⋅ 阅读:(35) ⋅ 点赞:(0)
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Collections.Generic;
using System;
using System.Collections;

public class ScreenshotManager : MonoBehaviour
{
    [Header("UI 设置")]
    public RawImage latestScreenshotDisplay; // 显示最新截图
    public Transform screenshotListContainer; // 存放历史截图的父物体(如 ScrollView Content)
    public GameObject screenshotThumbnailPrefab; // 截图缩略图 Prefab

    private string screenshotFolder;
    private List<Texture2D> screenshotTextures = new List<Texture2D>();

    void Start()
    {
        screenshotFolder = Path.Combine(Application.persistentDataPath, "Screenshots");
        Directory.CreateDirectory(screenshotFolder);

        // 加载之前保存的截图(可选)
        LoadExistingScreenshots();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F1))
        {
            CaptureScreenshot();
        }
    }

    public void CaptureScreenshot()
    {
        StartCoroutine(TakeScreenshotCoroutine());
    }

    private IEnumerator TakeScreenshotCoroutine()
    {
        yield return new WaitForEndOfFrame();

        // 1. 截取屏幕
        Texture2D screenshotTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        screenshotTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        screenshotTexture.Apply();

        // 2. 保存到文件
        string fileName = $"Screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
        string filePath = Path.Combine(screenshotFolder, fileName);
        byte[] bytes = screenshotTexture.EncodeToPNG();
        File.WriteAllBytes(filePath, bytes);

        // 3. 存储到列表
        screenshotTextures.Add(screenshotTexture);

        // 4. 更新 UI
        UpdateScreenshotUI(screenshotTexture);

        Debug.Log($"截图已保存: {filePath}");
    }

    private void UpdateScreenshotUI(Texture2D newScreenshot)
    {
        // 显示最新截图
        if (latestScreenshotDisplay != null)
        {
            latestScreenshotDisplay.texture = newScreenshot;
            latestScreenshotDisplay.SetNativeSize();
        }

        // 添加到历史列表(生成缩略图)
        if (screenshotListContainer != null && screenshotThumbnailPrefab != null)
        {
            GameObject thumbnailObj = Instantiate(screenshotThumbnailPrefab, screenshotListContainer);
            RawImage thumbnailImage = thumbnailObj.GetComponent<RawImage>();
            if (thumbnailImage != null)
            {
                thumbnailImage.texture = newScreenshot;
            }
        }
    }

    // 加载已存在的截图(可选)
    private void LoadExistingScreenshots()
    {
        string[] files = Directory.GetFiles(screenshotFolder, "*.png");
        foreach (string file in files)
        {
            byte[] fileData = File.ReadAllBytes(file);
            Texture2D texture = new Texture2D(2, 2);
            texture.LoadImage(fileData); // 自动调整尺寸
            screenshotTextures.Add(texture);
            UpdateScreenshotUI(texture);
        }
    }
}

创建 ScrollView(用于显示历史截图列表):

右键 Hierarchy → UI → ScrollView。

调整大小,确保能容纳多个缩略图。

创建缩略图 Prefab:

右键 Hierarchy → UI → RawImage(命名为 ScreenshotThumbnail)。

调整大小(如 200x200),并添加 Button 组件(方便点击查看大图)。

将其拖入 Resources 文件夹或直接拖到 screenshotThumbnailPrefab 字段。

配置脚本参数:

latestScreenshotDisplay → 拖入一个 RawImage(用于显示最新截图)。

screenshotListContainer → 拖入 ScrollView/Content。

screenshotThumbnailPrefab → 拖入你的缩略图 Prefab。

在这里插入图片描述
下面代码是可以按下F1不停保存截图,按下A键后一次生成

using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Collections.Generic;
using System;
using System.Collections;
using System.Linq;

public class ScreenshotManager : MonoBehaviour
{
    [Header("UI 设置")]
    public RawImage latestScreenshotDisplay; // 显示最新截图
    public Transform screenshotListContainer; // 存放历史截图的父物体(如 ScrollView Content)
    public GameObject screenshotThumbnailPrefab; // 截图缩略图 Prefab

    private string screenshotFolder;
    private List<string> screenshotPaths = new List<string>(); // 改为存储文件路径

    void Start()
    {
        screenshotFolder = Path.Combine(Application.persistentDataPath, "Screenshots");
        Directory.CreateDirectory(screenshotFolder);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F1))
        {
            CaptureScreenshot();
        }

        if (Input.GetKeyDown(KeyCode.A))
        {
            LoadAllScreenshotsToUI();
        }
    }

    public void CaptureScreenshot()
    {
        StartCoroutine(TakeScreenshotCoroutine());
    }

    private IEnumerator TakeScreenshotCoroutine()
    {
        yield return new WaitForEndOfFrame();

        // 1. 截取屏幕
        Texture2D screenshotTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        screenshotTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        screenshotTexture.Apply();

        // 2. 保存到文件
        string fileName = $"Screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
        string filePath = Path.Combine(screenshotFolder, fileName);
        byte[] bytes = screenshotTexture.EncodeToPNG();
        File.WriteAllBytes(filePath, bytes);

        // 3. 添加到路径列表(不立即显示UI)
        screenshotPaths.Add(filePath);

        // 4. 释放纹理内存
        Destroy(screenshotTexture);

        Debug.Log($"截图已保存: {filePath}");
    }

    private void LoadAllScreenshotsToUI()
    {
        // 1. 清空现有UI
        foreach (Transform child in screenshotListContainer)
        {
            Destroy(child.gameObject);
        }

        // 2. 获取所有截图文件并按时间排序
        var allScreenshots = Directory.GetFiles(screenshotFolder, "*.png")
                                    .OrderBy(f => new FileInfo(f).CreationTime)
                                    .ToList();

        // 3. 加载并显示所有截图
        StartCoroutine(LoadAndDisplayScreenshots(allScreenshots));
    }

    private IEnumerator LoadAndDisplayScreenshots(List<string> paths)
    {
        foreach (string filePath in paths)
        {
            // 1. 加载图片文件
            byte[] fileData = File.ReadAllBytes(filePath);
            Texture2D texture = new Texture2D(2, 2);
            texture.LoadImage(fileData);

            // 2. 创建UI元素
            GameObject thumbnailObj = Instantiate(screenshotThumbnailPrefab, screenshotListContainer);
            RawImage thumbnailImage = thumbnailObj.GetComponent<RawImage>();
            if (thumbnailImage != null)
            {
                thumbnailImage.texture = texture;
            }

            // 3. 如果是最后一个截图,显示在大图预览
            if (paths.Last() == filePath && latestScreenshotDisplay != null)
            {
                latestScreenshotDisplay.texture = texture;
                latestScreenshotDisplay.SetNativeSize();
            }

            yield return null; // 分帧加载避免卡顿
        }
    }
}