WXMC/.svn/pristine/3b/3b4f6004673f04940925a11f35d48b7cf3ff75a1.svn-base
2024-12-04 16:18:46 +08:00

48 lines
1.5 KiB
Plaintext

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PhotoBtn : MonoBehaviour
{
public Camera screenshotCamera;
private Button photoButton;
// Start is called before the first frame update
void Start()
{
photoButton = transform.GetComponent<Button>();
photoButton.onClick.AddListener(PhotoButtonClick);
}
void PhotoButtonClick()
{
// 创建一个Texture2D来保存截图
Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
// 将截图相机渲染到纹理上
RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
screenshotCamera.targetTexture = renderTexture;
screenshotCamera.Render();
// 将纹理内容读取到Texture2D
RenderTexture.active = renderTexture;
screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
// 解绑纹理
screenshotCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(renderTexture);
// 应用到Texture2D
screenshot.Apply();
// 保存为PNG文件
byte[] bytes = screenshot.EncodeToPNG();
string fileName = "Screenshot_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".png";
string filePath = Application.persistentDataPath + "/" + fileName;
System.IO.File.WriteAllBytes(filePath, bytes);
Debug.Log("Screenshot saved at: " + filePath);
}
}