这个题目不是很大,但是用的东西还是很多的。上代码
先定义一个Texture2D来存放图片,再来一个对象放贴图
public Texture2D myTex;
public GameObject myTexAdd;
void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 100, 100), "截图"))
{
Application.CaptureScreenshot(Application.streamingAssetsPath+"\\A.png");//截图函数
//使用WWW的时候一定要注意加上"file:///"来声明路径,否则不予通过
StartCoroutine(LoadImage("file:///" + Application.streamingAssetsPath+"\\A.png"));//使用协程来读取图片
}
}
IEnumerator LoadImage(string Path)//开始协程
{
WWW www = new WWW(Path);
yield return www;//当图片读取完成之后,开始读取
myTex = www.texture;
}
话说WWW类还真是比较方便。
myTexAdd.gameObject.renderer.material.mainTexture = myTex;
但是最后,发现如果图片(A.png)不存在,会出现错误。经检查是图片还没有来得及创建。
我们使用下面的方法
IEnumerator LoadImage(string Path)//开始协程
{
yield return new WaitForSeconds(1f);
WWW www = new WWW(Path);
yield return www;//当图片读取完成之后,开始读取
myTex = www.texture;
myTexAdd.gameObject.renderer.material.mainTexture = myTex;
}
这个只是权宜之计,通过强行停止1s等待图片创建。如果有检测图片是否创建好的函数就好了。
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
上面那种方法存在问题。我们不应该直接调用CaptureScreenshot()方法,这个方法创建文件需要耗费很多时间,体验非常不良好。
我们应该使用下面这种方法,先将屏幕图像存到Texture中,贴上去之后后保存(方法来自于menuconfig,感谢大神!)
IEnumerator GetCapture()
{
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, true);
byte[] imagebytes = tex.EncodeToPNG();//转化为png图
tex.Compress(false);//对屏幕缓存进行压缩
myTexAdd.renderer.material.mainTexture = tex;//对屏幕缓存进行显示(缩略图)
File.WriteAllBytes(Application.streamingAssetsPath + "/screencapture.png", imagebytes);//存储png
}