Unity3D 截图功能(1屏幕区域截图,2两张图片的合成)
先看效果 1.
看图 我想把图片 区域 的位置截图出来,
效果 2
看图,他二维码图片 放在 Texture2D 目标区域
现在我们来实行相关功能!
效果1:
/// <summary>
/// 传入一个 RectTransform 区域!, 就不把资格区域的图像保存下来
/// </summary>
/// <param name="rect"></param>
public void OnShowTexture(RectTransform rect)
{
///要现实的位置 RrctTransform, 转化到屏幕坐标。
Vector3 vect = RectTransformUtility.WorldToScreenPoint(Camera.main, rect.gameObject.transform.position);
Canvas canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
float radio = Screen.width / canvasScaler.referenceResolution.x;//适配
float x = vect.x - rect.sizeDelta.x * rect.pivot.x * radio;
float y = vect.y - rect.sizeDelta.y * rect.pivot.x * radio;
targetRect = new Rect(x, y, rect.sizeDelta.x * radio, rect.sizeDelta.y * radio);
Debug.Log(string.Format("x:{0}, y:{1}, width:{2}, height:{3}", targetRect.x, targetRect.y, targetRect.width, targetRect.height));
StartCoroutine(UploadPNG());
}
IEnumerator UploadPNG()
{
yield return new WaitForEndOfFrame();
Texture2D tex = new Texture2D((int)targetRect.width, (int)targetRect.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect((int)targetRect.x, (int)targetRect.y, (int)targetRect.width, (int)targetRect.height), 0, 0);
tex.Apply();
string path = Application.persistentDataPath + "/onMobileSavedScreen.png";
Debug.Log(path);
File.WriteAllBytes(path, tex.EncodeToPNG());
}
效果2:
/// <summary>
/// 传入两张Texture2D 图片
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public Texture2D TwoToOne(Texture2D source, Texture2D target)
{
///显示位置
int startWidth = source.width / 2 - target.width / 2;
int startHeight = 35;
source.SetPixels32(startWidth, startHeight, target.width,target.height, target.GetPixels32());
source.Apply();
string path = Application.persistentDataPath + "/1111.png";
Debug.Log(path);
File.WriteAllBytes(path, source.EncodeToPNG());
return source;
}
以上两种方法, 都可以满足 目前看两种效率 相差不多。应为底层实现差不多!
这是两张保存的图片
---------------------