gpt4 book ai didi

c# - 将 RenderTexture 转换为 Texture2D

转载 作者:太空狗 更新时间:2023-10-29 21:04:01 27 4
gpt4 key购买 nike

我需要将 RenderTexture 对象保存到 .png 文件,然后将其用作纹理来包裹 3D 对象。我的问题是现在我无法使用 EncodeToPNG() 保存 RenderTexture 对象,因为 RenderTexture 不包含该方法。如何将 RenderTexture 对象转换为 Texture2D 对象?谢谢!

// Saves texture as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;

public class SaveTexture : MonoBehaviour {

public RenderTexture tex;

// Save Texture as PNG
void SaveTexturePNG()
{
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);

// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
}
}

最佳答案

创建新的Texture2D,使用RenderTexture.ReadPixelsRenderTexture读取像素到新的Texture2D。最后,调用 Texture2D.Apply(); 应用更改后的像素。

Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
// ReadPixels looks at the active RenderTexture.
RenderTexture.active = rTex;
tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
tex.Apply();
return tex;
}

用法:

public RenderTexture tex;
Texture2D myTexture = toTexture2D(tex);

你可以让它成为一个扩展方法(恢复之前活跃的RenderTexture以避免意外):

public static class ExtensionMethod
{
public static Texture2D toTexture2D(this RenderTexture rTex)
{
Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
var old_rt = RenderTexture.active;
RenderTexture.active = rTex;

tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
tex.Apply();

RenderTexture.active = old_rt;
return tex;
}
}

用法:

public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();

关于c# - 将 RenderTexture 转换为 Texture2D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264468/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com