Unity3D本身内置了一个截屏并保存为图片的功能:
public static void CaptureScreenshot(string filename, int superSize = 0);
然而,在配合微信做截屏分享的时候,发现这个简单的静态函数并不能顺利实现功能逻辑,关键原因在于这个函数的实现是异步的,也就是说,你想要的截图并不会在这个函数调用后立即生成!尤其是在移动平台上,这个函数的延迟可能更大,而且更悲剧的是:这个函数并没有让调用方知道截图生成ok了的机制,比如回调等,所以,在参考了网上的资料后,还是自己实现了一个截图保存的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | StartCoroutine(CaptureScreen()); ... public IEnumerator CaptureScreen() { string ssname = "lastss.png" ; string sspath = Path.Combine(Application.temporaryCachePath, ssname); if (File.Exists(sspath)) { File.Delete(sspath); Debug.Log(ssname + " deleted first!" ); } Texture2D texture1; byte [] bytes; // Wait for screen rendering to complete yield return new WaitForEndOfFrame(); texture1 = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false ); texture1.ReadPixels( new Rect(0, 0, Screen.width, Screen.height), 0, 0); texture1.Apply(); yield return 0; bytes = texture1.EncodeToPNG(); File.WriteAllBytes(sspath, bytes); Debug.Log( "Screenshot saved: " + sspath); DoWeChatShareImage(sspath, "img" , true ); } |
这个函数以协同异步方式实现,首先等待EndOfFrame,确保所有渲染操作完成,然后通过ReadPixels读取渲染完成的帧缓冲上的像素信息,并生成PNG图片保存到指定路径(这里我用的是应用的cache路径,随时可被清除!),这样通过一个同步的文件IO操作,确保了在调用微信分享图片时,截图图片的可用性!
博主友情提示:
如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。
加载更多