public override void OnPointerDown(Vector3 position)
{
base.OnPointerDown(position);
toolBox.SetActive(false);
observeCamera.clearFlags = CameraClearFlags.SolidColor;//清除标记
string str = System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute + ":" + System.DateTime.Now.Second;
imgPath += "/" + System.DateTime.Now.Year + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Day + " " + str + ".png";
StartCoroutine(CaptureByCamera(observeCamera, new Rect(0, 0, Screen.width, Screen.height), imgPath));
}
/// <summary>
/// 截屏保存图片
/// </summary>
/// <param name="mCamera">渲染相机</param>
/// <param name="mRect">截屏区域大小</param>
/// <param name="filePath">保存路径</param>
/// <returns></returns>
private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string filePath)
{
yield return new WaitForEndOfFrame();
//设置RenderTexture
mCamera.gameObject.SetActive(true);
RenderTexture mRender = new RenderTexture((int)mRect.width, (int)mRect.height, 0);
mCamera.targetTexture = mRender;
mCamera.Render();
RenderTexture.active = mRender;
Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.ARGB32, false);
//读取屏幕像素
mTexture.ReadPixels(mRect, 0, 0);
mTexture.Apply();
mCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(mRender);
//转换成字节保存
byte[] bytes = mTexture.EncodeToPNG();
File.WriteAllBytes(filePath, bytes);
toolBox.SetActive(true);
mCamera.enabled = false;
mCamera.clearFlags = CameraClearFlags.Skybox;
}
unity 截屏并保存
最新推荐文章于 2024-08-10 15:55:30 发布
这篇博客详细介绍了如何在Unity中实现截屏并保存为图片的功能。通过OnPointerDown事件触发截图,使用DateTime获取当前时间作为文件名,利用Camera和RenderTexture进行截图操作,最后将Texture2D转换为PNG格式并保存到指定路径。
摘要由CSDN通过智能技术生成