当前位置: 首页 > news >正文

unity 截图并且展现在UI中

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; // 分帧加载避免卡顿
        }
    }
}

相关文章:

  • turtle的九个使用
  • 【数据分享】基于联合国城市化程度框架的全球城市边界数据集(免费获取/Shp格式)
  • Spring 拦截器(Interceptor)与过滤器(Filter)对比
  • 51c深度学习~合集4
  • 【学Rust写CAD】16 零标记类型(zero.rs)
  • linux scp复制多层级文件夹到另一服务器免密及脚本配置
  • 数据库基础(聚合函数 分组 排序)
  • 大型语言模型的秘密:思考链长度与提示格式的魔力
  • mmaction2的mmcv依赖安装教程
  • 探究 CSS 如何在HTML中工作
  • 马拉车算法
  • 存储管理(一)
  • Flutter Autocomplete 从入门到进阶:打造智能输入体验的完整指南
  • 远程连接电脑
  • week2|机器学习(吴恩达)学习笔记
  • 微服务间通信
  • 畅捷通T+与吉客云数据集成案例解析
  • 直流分量的产生以及危害,THD总谐波失真度的定义,有哪些危害
  • 蓝桥杯 子2023
  • 博卡软件管理中心8:为美容美发行业量身打造的轻量级管理方案
  • 长沙做企业网站的公司/泉州百度关键词排名
  • 深圳做商城网站/建网站教程
  • 网站开发商城图片上传/sns营销
  • 网络推广品牌营销公司/天津seo网站推广
  • 网站描述如何写利于优化/关键词拓展工具有哪些
  • 安徽省建设厅网站备案/怎么做app推广