Unity实现截屏以及根据相机画面截图
在游戏开发和软件开发中,经常需要截图的功能,分带UI的截图和不带UI的截图功能。代码如下:
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
publicstaticclassScreenShotForCamera{
publicstaticvoidCaptureScreen(string_path=null)
{
if(_path==null)
_path="Screenshot.png";
Application.CaptureScreenshot(_path,0);
}
publicstaticTexture2DCaptureScreen(Rectrect,bool_isCreatePhoto=false,string_path=null)
{
//先创建一个的空纹理,大小可根据实现需要来设置
Texture2DscreenShot=newTexture2D((int)rect.width,(int)rect.height,TextureFormat.RGB24,false);
//读取屏幕像素信息并存储为纹理数据,
screenShot.ReadPixels(rect,0,0);
screenShot.Apply();
//然后将这些纹理数据,成一个png图片文件
if(_isCreatePhoto)
{
if(_path==null)
_path=Application.dataPath+"/Screenshot.png";
byte[]bytes=screenShot.EncodeToPNG();
stringfilename=_path;
System.IO.File.WriteAllBytes(filename,bytes);
Debug.Log(string.Format("截屏了一张图片:{0}",filename));
}
//最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。
returnscreenShot;
}
//
publicstaticTexture2DCaptureCamera(refCamera_camera,Rect_rect,int_destX,int_destY,bool_isCreatePhoto=false,string_path=null)
{
RenderTexturerenderTexture=newRenderTexture((int)_rect.width,(int)_rect.height,24,RenderTextureFormat.ARGB32);
_camera.targetTexture=renderTexture;
_camera.Render();
//激活这个renderTexture,并从中中读取像素
RenderTexture.active=_camera.targetTexture;
Texture2DscreenShot=newTexture2D((int)_rect.width,(int)_rect.height,TextureFormat.ARGB32,false);
screenShot.ReadPixels(_rect,_destX,_destY);//从(_destX,_destY)坐标开始读取_rect大小的图片
screenShot.Apply();
//重置参数
//_camera.targetTexture=null;
RenderTexture.active=null;
//GameObject.Destroy(renderTexture);
//生成PNG图片
if(_isCreatePhoto)
{
if(_path==null)
_path=Application.dataPath+"/Screenshot.png";
byte[]bytes=screenShot.EncodeToPNG();
stringfilename=_path;
System.IO.File.WriteAllBytes(filename,bytes);
Debug.Log(string.Format("截屏了一张照片:{0}",filename));
}
returnscreenShot;
}
}
小编再为大家分享一段:Unity实现截屏功能,希望可以帮到大家
publicclassScreenShot:MonoBehaviour
{
voidOnScreenShotClick()
{
//得到当前系统时间
System.DateTimenow=System.DateTime.Now;
stringtimes=now.ToString();
//去掉前后空格
times=times.Trim();
//将斜杠替换成横杠
times=times.Replace("/","-");
stringfileName="ARScreenShot"+times+".png";
//判断该平台是否为安卓平台
if(Application.platform==RuntimePlatform.Android)
{
//参数依次为屏幕宽度屏幕高度纹理格式是否使用映射
Texture2Dtexture=newTexture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
//读取贴图
texture.ReadPixels(newRect(0,0,Screen.width,Screen.height),0,0);
//应用截屏
texture.Apply();
//将对象序列化
byte[]bytes=texture.EncodeToPNG();
//设定存储到的手机文件夹路径
stringdestination="/sdcard/DCIM/Screenshots";
//如果不存在该文件夹
if(!Directory.Exists(destination))
{
//创建该文件夹
Directory.CreateDirectory(destination);
}
stringpathSave=destination+"/"+fileName;
File.WriteAllBytes(pathSave,bytes);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。