参考文章:【Unity】Unity中通过纹理截屏将图片保存到本地_Zok93-CSDN博客
方法一:截取全屏
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LXTest : MonoBehaviour
{
Texture2D screenShot;//保存截取的纹理
public Transform tra;//显示截屏的3D对象
public Image image; //显示截屏的Image
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(ScrrenCapture(new Rect(0, 0, Screen.width, Screen.height)));
}
}
IEnumerator ScrrenCapture(Rect rect)
{
screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
yield return new WaitForEndOfFrame();
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
Sprite sp = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f), 100.0f);
image.sprite = sp;
// tra.GetComponent<MeshRenderer>().material.mainTexture = screenShot;
}
}
方法二:根据区域进行截屏
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LXCatchScreenImage : MonoBehaviour
{
public Image TargetImage;//想要截取的目标区域
public Image ShowImage; //截取后用来显示的Iamge
Texture2D screenShot; //存储截取的纹理
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(CaptureGUIPNG());
}
}
// 定义一个协程
IEnumerator CaptureGUIPNG()
{
// 因为"WaitForEndOfFrame"在OnGUI之后执行
// 所以我们只在渲染完成之后才读取屏幕上的画面
yield return new WaitForEndOfFrame();
var rect = TargetImage.GetComponent<RectTransform>();
int width = (int)rect.sizeDelta.x;
int height = (int)rect.sizeDelta.y;
var startx = rect.position.x - (width / 2) * rect.localScale.x;
var starty = rect.position.y - (height / 2) * rect.localScale.y;
if (startx + width > Screen.width)
width = (int)Mathf.Floor(Screen.width - startx);
if (starty + height > Screen.height)
height = (int)Mathf.Floor(Screen.height - starty);
// 创建一个屏幕大小的纹理,RGB24 位格(24位格没有透明通道,32位的有)
screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
// 读取屏幕内容到我们自定义的纹理图片中
screenShot.ReadPixels(new Rect(startx, starty, width, height), 0, 0);
// 保存前面对纹理的修改
screenShot.Apply();
// 编码纹理为PNG格式
//byte[] bytes = screenShot.EncodeToPNG();
// 销毁无用的图片纹理
//Destroy(tex);
Sprite sp = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f), 100.0f);
ShowImage.sprite = sp;
}
}