unity中 截图的两种常用方式 区域截图和相机截图
区域截图:可以截图区域内全部元素
相机截图:可以截图区域内自己想要的元素
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenTexture : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
/// <summary>
/// 区域截图
/// </summary>
/// <param name="rectT"></param>
/// <param name="ac"></param>
/// <returns></returns>
public IEnumerator GetScreenTexture(RectTransform rectT, Action<Texture2D> ac)
{
yield return new WaitForEndOfFrame();
Texture2D screenShot = new Texture2D((int)rectT.rect.width, (int)rectT.rect.height, TextureFormat.RGB24, true);
float x = rectT.anchoredPosition3D.x;// + (Screen.width - rectT.rect.width) / 2;//锚点在左下角
float y = rectT.anchoredPosition3D.y; //+ (Screen.height - rectT.rect.height) / 2;
Rect position = new Rect(x, y, rectT.rect.width, rectT.rect.height);
screenShot.ReadPixels(position, 0, 0, true);//按照设定区域读取像素;注意是以左下角为原点读取
screenShot.Apply();
ac(screenShot);//回调函数
//string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
//string filePath = "";
//filePath = Application.streamingAssetsPath + "/HeadFold";
//string scrPathName = filePath + "/" + fileName;
//if (!Directory.Exists(filePath))
//{
// Directory.CreateDirectory(filePath);
//}
二进制转换
//byte[] byt = screenShot.EncodeToJPG();
//File.WriteAllBytes(scrPathName, byt);
}
public Camera camera1;
/// <summary>
/// 相机截图
///
/// </summary>
/// <param name="rectT"></param>
/// <param name="ac"></param>
/// <returns></returns>
public IEnumerator GetScreenCanTexture(RectTransform rectT, Action<Texture2D> ac)
{
yield return new WaitForEndOfFrame();
Texture2D screenShot = new Texture2D(100, 100);
Rect rect = new Rect(0, 0, rectT.rect.width, rectT.rect.height);
RenderTexture rt = new RenderTexture((int)(Screen.width), (int)(Screen.height), 0);//先设置一个RenderTexture,大小为屏幕分辨率
camera1.targetTexture = rt;
camera1.Render();//手动开启截图相机的渲染
RenderTexture.active = rt;//激活这个RenderTexture
//验算是否超出屏幕渲染,如果超出则取最大边界
//float width = rect.width + rect.x > Screen.width ? Screen.width - rect.x : rect.width;
//float height = rect.height + rect.y > Screen.height ? Screen.height - rect.y : rect.height;
float x = rectT.anchoredPosition3D.x;//锚点在左下角
float y = rectT.anchoredPosition3D.y;
Rect position = new Rect(x, y, rect.width, rect.height);
//新建一个模板Texture2D等待相机渲染图像,设定Textrue2D的大小为我们需要的大小
screenShot = new Texture2D((int)rectT.rect.width, (int)rectT.rect.height, TextureFormat.RGB24, false);
// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.ReadPixels(position, 0, 0);//按照设定区域读取像素;注意是以左下角为原点读取
screenShot.Apply();//保存像素信息
ac(screenShot); //回调函数
camera1.targetTexture = null; // 重置相关参数,以使用camera继续在屏幕上显示
RenderTexture.active = null;
Destroy(rt);
}
}