游戏开发项目中会有截屏这样的功能,目前来看,一共有三种方式。
第一种方式:截取某一帧时整个游戏的画面,或者说时全屏截图。
特点:1、不能针对某一个相机的画面进行截图
2、对局部画面截图实现起来不方便,效率也很低,基本不建议再项目中使用。
//代码
private void CaptureByUnity(string mFileName)
{Application.CaptureScreenshot(mFileName);
}
第二种方法就是使用Textured2d类下面的相关方法,实现截屏功能。根据rect设置的参数进行相关截屏
代码:
/// <summary>
/// 根据一个Rect类型来截取指定范围得屏幕
/// 左下角为(0,0)原点
/// </summary>
/// <param name="mRect"></param>
/// <param name="mFileName"></param>
/// <returns></returns>
private IEnumerator CaptureByRect(Rect mRect,string mFileName)
{
yield return new WaitForEndOfFrame(); //等待渲染线程结束
Texture2D mTexture = new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false); //初始化Texture2D图片
mTexture.ReadPixels(mRect,0,0); //读取屏幕像素信息并且存储为纹理数据
mTexture.Apply(); //应用
byte[] bytes = mTexture.EncodeToPNG(); //将图片信息编码为字节信息
System.IO.File.WriteAllBytes(mFileName,bytes); //保存
//return mTexture; //如果需要可以返回截图
}
第三种方法,针对某个相机进行截图,思路是这样的,可以选择特定相机进行截屏。比如我们将分出一个camera来专门显示UI界面,用另外一个camera相机显示场景画面。最后,我们只对场景相机进行截屏。关键在于如何实现对某个相机进行截屏。这种方式用的是RenderTexture类。
代码
private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string mFileName)
{
yield return new WaitForEndOfFrame(); //等待线程结束
RenderTexture mRender = new RenderTexture((int)mRect.width,(int)mRect.height,0); //初始化RenderTexture
mCamera.targetTexture = mRender; //设置相机得渲染目标
mCamera.Render(); //开始渲染
RenderTexture.active = mRender; //激活渲染贴图读取信息
Texture2D mTexture = new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false);
mTexture.ReadPixels(mRect,0,0); //读取截屏像素信息并存储为纹理数据
mTexture.Apply(); //应用
//释放相机 销毁渲染贴图
mCamera.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(mRender);
byte[] bytes = mTexture.EncodeToPNG(); //将图片信息编码为字节信息
System.IO.File.WriteAllBytes(mFileName,bytes); //保存
//return mTexture; //如果需要可以返回截图
}
效果如下:
ScreenShot01
ScreenShot02
截取中间四分之一
CaptureByRect(newRect(Screen.width.0.25f,Screen.height*0.25f,Screen.width*0.5f,Screen.height*0.5f),string mFileName)
效果:
截取全屏
CaptureByRect(newRect(Screen.width.0f,Screen.height*0f,Screen.width*1f,Screen.height*1f),string mFileName)
ScreenShot03
以上就是Unity3D中的截屏方法。