csharp
using UnityEngine;
using System.IO;
public class ScreenCaptureWithAlpha : MonoBehaviour
{
// 设置保存路径和文件名
public string fileName = "ScreenCaptureWithAlpha.png";
public string savePath = "Screenshots/";
// 相机引用(需要确保相机支持 Alpha 通道)
public Camera captureCamera;
void Start()
{
// 如果没有指定相机,默认使用主相机
if (captureCamera == null)
{
captureCamera = Camera.main;
}
// 确保保存路径存在
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
}
void Update()
{
// 按下指定键(例如 S 键)时捕获屏幕
if (Input.GetKeyDown(KeyCode.S))
{
CaptureScreenWithAlpha();
}
}
void CaptureScreenWithAlpha()
{
// 获取屏幕分辨率
int width = Screen.width;
int height = Screen.height;
// 创建一个支持 Alpha 通道的 RenderTexture
RenderTexture renderTexture = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
renderTexture.antiAliasing = 1; // 可选:设置抗锯齿
renderTexture.Create();
// 将相机的渲染目标设置为 RenderTexture
captureCamera.targetTexture = renderTexture;
captureCamera.clearFlags = CameraClearFlags.SolidColor; // 确保背景是透明的
captureCamera.backgroundColor = new Color(0, 0, 0, 0); // 设置背景为透明
// 渲染相机内容到 RenderTexture
captureCamera.Render();
// 创建一个 Texture2D 来存储捕获的图像
Texture2D screenShot = new Texture2D(width, height, TextureFormat.ARGB32, false);
// 将 RenderTexture 的内容读取到 Texture2D
RenderTexture.active = renderTexture;
screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
screenShot.Apply();
// 清理资源
captureCamera.targetTexture = null;
RenderTexture.active = null;
renderTexture.Release();
Destroy(renderTexture);
// 将 Texture2D 编码为 PNG 文件(支持 Alpha 通道)
byte[] bytes = screenShot.EncodeToPNG();
string fullPath = Path.Combine(savePath, fileName);
File.WriteAllBytes(fullPath, bytes);
// 销毁 Texture2D 对象
Destroy(screenShot);
Debug.Log($"屏幕截图已保存至: {fullPath}");
}
}