using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class CaptureComponent : MonoBehaviour
{
private Camera _uguiCamera;
private RectTransform rectTransform;
private string basePath;
private void Awake()
{
_uguiCamera = GameObject.FindGameObjectWithTag("GuiCamera").GetComponent<Camera>();
rectTransform = this.GetComponent<RectTransform>();
basePath = Application.persistentDataPath + "/share/";
if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
}
public void CaptureScreenByRect(Action<string> cb,string name="")
{
if (string.IsNullOrEmpty(name))
{
name = basePath + UnityExtends.Calculationmd5(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"))+".png";
}
StartCoroutine(CaptureScreenAsync(name, cb));
}
public IEnumerator CaptureScreenAsync(string path, Action<string> cb)
{
yield return new WaitForEndOfFrame();
try
{
if (path != "")
{
Rect rect = rectTransform.rect;
Vector3 startWorldPos = rectTransform.TransformPoint(rect.x, rect.y, 0);
Vector3 endWorldPos = rectTransform.TransformPoint(rect.x + rect.width, rect.y + rect.height,0);
startWorldPos.z = 0;
endWorldPos.z = 0;
Vector3 startViewPos = _uguiCamera.WorldToViewportPoint(startWorldPos);
Vector3 endViewPos = _uguiCamera.WorldToViewportPoint(endWorldPos);
rect.x = Screen.width * startViewPos.x;
rect.y = Screen.height * startViewPos.y;
rect.width = Screen.width * (endViewPos.x - startViewPos.x);
rect.height = Screen.height * (endViewPos.y - startViewPos.y);
if (rect.x < 0 || rect.y < 0 || (rect.x + rect.width) > Screen.width || (rect.y + rect.height) > Screen.height)
{
//读取屏幕像素越界,界面不要超过屏幕显示区域
Debug.Log("窗体超过屏幕");
cb?.Invoke("");
}
else
{
//Debug.Log(rect.width + " " + rect.height);
Texture2D capture = new Texture2D((int)(rect.width), (int)(rect.height), TextureFormat.RGB24, false);
capture.ReadPixels(rect, 0, 0);
capture.Apply();
byte[] datas = capture.EncodeToPNG();
File.WriteAllBytes(path, datas);
if (cb != null)
{
Debug.Log(path);
cb(path);
}
}
}
else
cb?.Invoke("");
}
catch (Exception e)
{
Debug.LogError("CaptureScreenByRect:" + e.Message);
}
}
}