FM/Assets/Test/CanvasToPNGExporter.cs

53 lines
1.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// using UnityEngine;
// using UnityEngine.UI;
// using System.IO;
//
// public class CanvasToPNGExporter : MonoBehaviour
// {
// [Header("导出设置")]
// public Canvas targetCanvas; // 要导出的 Canvas
// public Vector2Int outputResolution = new Vector2Int(1024, 1024);
// public string fileName = "UIExport";
// public string saveFolder = "Exports";
//
// [ContextMenu("导出 Canvas 为图片")]
// public void ExportCanvasToImage()
// {
// if (targetCanvas == null)
// {
// Debug.LogError("❌ 未指定 Canvas");
// return;
// }
//
// // 创建 RenderTexture
// RenderTexture rt = new RenderTexture(outputResolution.x, outputResolution.y, 0, RenderTextureFormat.ARGB32);
// rt.Create();
//
// // ✅ 使用 Unity 6 新功能:将 Canvas 渲染进 RenderTexture
// targetCanvas.RenderToTexture(rt);
//
// // 读取像素数据
// RenderTexture currentRT = RenderTexture.active;
// RenderTexture.active = rt;
//
// Texture2D tex = new Texture2D(outputResolution.x, outputResolution.y, TextureFormat.RGBA32, false);
// tex.ReadPixels(new Rect(0, 0, outputResolution.x, outputResolution.y), 0, 0);
// tex.Apply();
//
// RenderTexture.active = currentRT;
//
// // 保存为 PNG
// string dir = Path.Combine(Application.dataPath, saveFolder);
// Directory.CreateDirectory(dir);
// string fullPath = Path.Combine(dir, fileName + ".png");
//
// File.WriteAllBytes(fullPath, tex.EncodeToPNG());
//
// Debug.Log($"✅ Canvas 导出成功:{fullPath}");
//
// // 清理资源
// rt.Release();
// DestroyImmediate(rt);
// DestroyImmediate(tex);
// }
// }