将RenderTexture转换为Texture2D [英] Convert RenderTexture to Texture2D

查看:2260
本文介绍了将RenderTexture转换为Texture2D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to save a RenderTexture object to a .png file that will then be used as a texture to wrap about a 3D object. My problem is right now I can't save a RenderTexture object using EncodeToPNG() because RenderTexture doesn't include that method. How can I convert a RenderTexture object into a Texture2D object? Thank you!

// 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.ReadPixels RenderTexture 进入新的 Texture2D 。最后,调用 Texture2D.Apply(); 来应用更改的像素。

Create new Texture2D, use RenderTexture.ReadPixels to read the pixels from RenderTexture into the new Texture2D. Finally, Call Texture2D.Apply(); to apply the changed pixels.

Texture2D toTexture2D(RenderTexture rTex)
{
    Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
    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);






您可以将其作为扩展方法:


You can make it an extension method:

public static class ExtensionMethod
{
    public static Texture2D toTexture2D(this RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
        RenderTexture.active = rTex;
        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();
        return tex;
    }
}

用法:

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

这篇关于将RenderTexture转换为Texture2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆