在Unity3D中利用 RenderTexture 实现游戏内截图

https://my.oschina.net/u/4316056/blog/4002529

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class 截图 : MonoBehaviour {

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("Save");
            Save();
        }
    }

    private RenderTexture TargetTexture;

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        TargetTexture = source;
        Graphics.Blit(source, destination);
    }

    private void Save()
    {
        RenderTexture.active = TargetTexture;

        Texture2D png = new Texture2D(RenderTexture.active.width, RenderTexture.active.height, TextureFormat.ARGB32, true);
        png.ReadPixels(new Rect(0, 0, RenderTexture.active.width, RenderTexture.active.height), 0, 0);

        byte[] bytes = png.EncodeToPNG();
        string path = string.Format(@"D:\123.png");
        FileStream file = File.Open(path, FileMode.Create);
        BinaryWriter writer = new BinaryWriter(file);
        writer.Write(bytes);
        file.Close();
        writer.Close();

        Destroy(png);
        png = null;

        Debug.Log("Save Down");
    }
}

  

posted @ 2021-01-12 14:53  00000000O  阅读(385)  评论(0)    收藏  举报