using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Rendering;
public class RTDemo2 : MonoBehaviour
{
public GameObject m_cube;
public Camera m_camera;
public Shader m_shader;
private Mesh m_cubeMesh;
private int m_rtID;
private CommandBuffer m_cmd;
private Material m_material;
private void Start()
{
MeshFilter mr = m_cube.GetComponent<MeshFilter>();
m_cubeMesh = mr.sharedMesh;
m_rtID = Shader.PropertyToID("xxxxxx2");
m_cmd = new CommandBuffer();
m_cmd.name = "ddd";
m_material = new Material(m_shader);
m_camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, m_cmd);
}
RenderTexture rt;
bool save = false;
int i = 0;
private void OnPostRender()
{
m_cmd.Clear();
m_cmd.GetTemporaryRT(m_rtID, Screen.width, Screen.height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32);
m_cmd.SetRenderTarget(m_rtID);
m_cmd.ClearRenderTarget(true, true, Color.red);
Matrix4x4 m = Matrix4x4.identity;
m.SetTRS(m_cube.transform.position, Quaternion.identity, m_cube.transform.localScale);
m_cmd.DrawMesh(m_cubeMesh, m, m_material);
if (rt == null)
{
rt = new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.ARGB32);
rt.name = "2333";
}
m_cmd.Blit(m_rtID, rt);
m_cmd.Blit(rt, m_camera.targetTexture);
if (i<=1) //这里不知道为啥一定要等一帧
{
i++;
save = true;
RenderTexture.active = rt;
Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.RGBAHalf, false);
png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
png.Apply();
Color r = png.GetPixel(0, 0);
for (int i = 0; i < 400; ++i)
{
for (int j = 0; j < 300; ++j)
{
png.SetPixel(i, j, Color.blue);
}
}
byte[] bytes = png.EncodeToPNG();
string dir = Application.dataPath + "/xx";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
FileStream file = File.Open(dir + "/" + "333" + ".png", FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(png);
png = null;
}
}
}
保存一个RenderTexture到一个png
最新推荐文章于 2024-03-05 13:02:58 发布