截屏原理:Camera(摄像机)是Unity中非常重要的一个组件,其中有一个属性叫做targetTexture,在设置了targetTexture后,Camera会在渲染时将其屏幕上的图像渲染到targetTexture上,预览截屏时将texture赋值给UI Texture组件即可看到截屏。当要保存截图时可以将texture转化为Png格式的图片
截屏:
public void startScreenShot(GameObject camera, GameObject uicamera, System.Action callback = null)
{
string times = System.DateTime.Now.Millisecond.ToString();
filename = times + ".png";
uicamera.GetComponent<Camera>().enabled = true;
StartCoroutine(CaptureByCamrea(camera.GetComponent<Camera>(), uicamera.GetComponent<Camera>(), new Rect(0, 0, Screen.width, Screen.height), callback));
}
private IEnumerator CaptureByCamrea(Camera camera, Camera camera2, Rect rt, System.Action func = null)
{
yield return new WaitForEndOfFrame();
RenderTexture render = new RenderTexture((int)rt.width, (int)rt.height, 1);
camera.targetTexture = render;
camera.Render();
camera2.targetTexture = render;
camera2.Render();
RenderTexture.active = render;
texture = new Texture2D((int)rt.width, (int)rt.height, TextureFormat.RGB24, false);
texture.ReadPixels(rt, 0, 0);
texture.Apply();
//temptexture = texture;
textureSize = texture.width * texture.height * 24 / 8;
camera.targetTexture = null;
camera2.targetTexture = null;
RenderTexture.active = null;
GameObject.DestroyImmediate(render); //立即删掉清除内存
if (func != null)
{
func.Invoke();
}
}
保存图片:
/// <summary>
/// 保存图片到相册
/// </summary>
public void SavePhoto()
{
string path = SavePhotoToLocal();
SDKManager.GetSdkInstance().SavePhoto(path);
System.IO.File.Delete(path);
}
/// <summary>
/// 保存图片到游戏目录
/// </summary>
public string SavePhotoToLocal()
{
byte[] bytes = texture.EncodeToPNG();
string mobilePath = Application.persistentDataPath + "/photo";
if (!Directory.Exists(mobilePath))
{
Directory.CreateDirectory(mobilePath);
}
m_path = mobilePath + "/" + filename;
System.IO.File.WriteAllBytes(m_path, bytes);
// ExternalMsgHandle.externalCallHandle.SavePhoto(m_path);
return m_path;
}
public void DeletePhoto()
{
if(!string.IsNullOrEmpty(m_path))
{
if(File.Exists(m_path))
System.IO.File.Delete(m_path);
}
}