在 Unity 的 URP(Universal Render Pipeline) 管线下,如果你想对屏幕进行拍照,并且保留 Alpha 通道信息,你需要使用 RenderTexture 和 Graphics.Blit 来复制当前相机的渲染内容到一个带有 Alpha 通道的纹理中。然后你可以将该纹理读取为 Texture2D 并保存为 PNG 文件(支持 Alpha 通道)。
✅ 实现目标:
- 拍照(截屏)
- 支持透明背景(保留 Alpha 通道)
- 使用 URP 渲染管线
📌 步骤说明:
- 创建一个带 Alpha 通道的 RenderTexture
- 将主相机渲染输出 Blit 到这个 RenderTexture
- 将 RenderTexture 内容读取到 Texture2D 中
- 保存为 PNG 文件(保留 Alpha)
🧾 示例代码:
using UnityEngine;
using System.IO;
public class ScreenCaptureWithAlpha : MonoBehaviour
{
public int captureWidth = 1024; // 截图宽度
public int captureHeight = 768; // 截图高度
// 截图并保存到本地
public void CaptureAndSave()
{
// 1. 创建 RenderTexture(需要启用 Color + Alpha)
RenderTexture renderTexture = new RenderTexture(captureWidth, captureHeight, 24, RenderTextureFormat.ARGB32);
renderTexture.Create();
// 2. 设置相机的 targetTexture
Camera mainCamera = Camera.main;
RenderTexture previousTarget = mainCamera.targetTexture;
mainCamera.targetTexture = renderTexture;
// 3. 强制渲染一帧
mainCamera.Render();
// 4. 创建 Texture2D 来读取 RenderTexture 数据
Texture2D texture = new Texture2D(captureWidth, captureHeight, TextureFormat.ARGB32, false);
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, captureWidth, captureHeight), 0, 0);
texture.Apply();
// 5. 恢复相机设置
mainCamera.targetTexture = previousTarget;
RenderTexture.active = null;
Object.Destroy(renderTexture);
// 6. 保存为 PNG(支持 Alpha)
byte[] bytes = texture.EncodeToPNG();
string filename = Path.Combine(Application.dataPath, "ScreenshotWithAlpha.png");
File.WriteAllBytes(filename, bytes);
Debug.Log("截图已保存至: " + filename);
// 可选:销毁临时 Texture2D
Object.Destroy(texture);
}
}
🔧 注意事项:
- RenderTextureFormat.ARGB32:确保包含 Alpha 通道。
- 如果你使用的是透明背景(比如 UI 或透明物体),确保场景中有透明物体或摄像机设置了 Clear Flags 为
Depth Only 或 Solid Color(颜色透明)。
- 在 Editor 中测试时,调用
CaptureAndSave() 方法即可截图保存。
📷 示例调用方式:
你可以在 Unity 编辑器中添加一个按钮来触发截图:
#if UNITY_EDITOR
[UnityEditor.MenuItem("Tools/Capture Screenshot With Alpha")]
static void MenuCapture()
{
var go = new GameObject("ScreenCapture").AddComponent<ScreenCaptureWithAlpha>();
go.CaptureAndSave();
DestroyImmediate(go);
}
#endif
📦 输出文件格式:
- 输出为
.png 格式,完全支持 Alpha 通道。
- 路径为:
Application.dataPath + "/ScreenshotWithAlpha.png"
如需进一步处理(例如上传服务器、UI 显示等),也可以直接使用 texture 对象作为图像资源。
如果你还有特定需求(如指定相机、裁剪区域、抗锯齿等),可以继续扩展这个脚本。
需要我帮你加上 UI 预览或者异步保存等功能吗?