第一步:全屏截取(方法很多,这里只写一种)
IEnumerator CaptrueTargetScreen(string picname, GameObject parent)
{
yield return new WaitForEndOfFrame();
if (null != Camera.main)
{
//#if ZSPACE
Rect rect = new Rect(new Vector2(0, 0), new Vector2(Screen.width,Screen.height)) ;
RenderTexture rt = new RenderTexture((int)rect.width,(int)rect.height, 0) ;
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
Camera camera = GameObject.Find("ZCameraRig/ZCamera").GetComponent<Camera>();
camera.targetTexture = rt;
camera.Render();
//ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
//ps: camera2.targetTexture = rt;
//ps: camera2.Render();
//ps: -------------------------------------------------------------------
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数,以使用camera继续在屏幕上显示
camera.targetTexture = null; //ps: camera2.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
Vector3 vleft = RectTransformUtility.WorldToScreenPoint(camera, Bottomleft.transform.position);
Vector3 vright = RectTransformUtility.WorldToScreenPoint(camera, Bottomright.transform.position);
Vector3 vtop = RectTransformUtility.WorldToScreenPoint(camera, Topleft.transform.position);
int width = (int)Mathf.Abs(vright.x - vleft.x);
int height = (int)Mathf.Abs(vtop.y - vleft.y);
RectInt cutScope = new RectInt((int)vleft.x, (int)vleft.y, width, height);
RectInt targetScope = new RectInt(0, 0, width, height);
Texture2D finalTex = CutOrCopyTexture(screenShot, cutScope, targetScope);
if (null != parent)
{
GameObject previewobj = Ywa_StaticFuns.FindInChild(parent, _PPTPreview, false);
previewobj.GetComponent<Image>().sprite = Sprite.Create(finalTex, new Rect(0, 0, finalTex.width, finalTex.height), Vector2.zero);
}
byte[] bytes = finalTex.EncodeToPNG();
string filename = Application.persistentDataPath + "/" + picname + ".png";
Debug.Log("filename:" + filename);
if (File.Exists(filename))
{
File.Delete(filename);
}
File.WriteAllBytes(filename, bytes);
}
}
第二步:将获得的全屏图片进行裁剪
/// <summary>
/// 裁剪图片
/// </summary>
/// <param name="source">被裁剪的原图片</param>
/// <param name="cutScope">原图片上被裁剪的位置</param>
/// <param name="targetScope">对应目标图片上的框位置</param>
/// <returns></returns>
Texture2D CutOrCopyTexture(Texture2D source, RectInt cutScope, RectInt targetScope)
{
Texture2D target = new Texture2D(targetScope.width, targetScope.height, source.format, false);
Graphics.CopyTexture(source, 0, 0, cutScope.x, cutScope.y, cutScope.width, cutScope.height, target, 0, 0, targetScope.x, targetScope.y);
return target;
}