先创建一个的空纹理,大小可根据实现需要设置。Texture2D texture2D = new Texture2D(int width, int height);
将相应的像素信息存储入这个新建的空纹理中。texture2D.ReadPixels或texture2D.SetPixels
最后,将所有像素信息,“申请”成正式的Texture2D类对象。texture2D.Apply();
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class jieping : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void jp_button()
{
// 创建一个 Rect 对象
Rect rect = new Rect(0, 0, Screen.width, Screen.height);
// 调用 CaptureScreenshot2 方法,并将返回的 Texture2D 对象赋给一个变量
Texture2D screen = CaptureScreenshot2(rect);
}
/// <summary>
/// Captures the screenshot2.
/// </summary>
/// <returns>The screenshot2.</returns>
/// <param name="rect">Rect.截图的区域,左下角为o点</param>
Texture2D CaptureScreenshot2(Rect rect)
{
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);//先创建一个的空纹理,大小可根据实现需要来设置
screenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
screenShot.Apply();
byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件
string filename = Application.dataPath + "/Screenshot.png";
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("截屏了一张图片: {0}", filename));
//最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。
return screenShot;
}
}