您的位置:首页 > 移动开发 > Unity3D

Unity3D -- 自定义范围截屏

2015-11-21 11:55 531 查看
大家都知道unity有一个截屏方法,调用Application.CaptureScreenshot("Screenshot.png")方法就可以截取一张图保存到Application.persistentDataPath + "/Screenshot.png",
但是如果你只是想截取屏幕固定部分的内容怎么办呢,而且那个固定部分还是使用程序动态算出来的,这个时候使用全屏截取就会有错误了。

Unity是可以实现截取固定位置屏幕的。

首先在UI下面建立一个面板,



基于父对象中心对齐,然后长宽自由设定,

在父对象中声明一个public RectTransform BackGround 变量,然后将上面设置的面板关联到BackGround。



程序运行是ShareUI设置面板大小

m_Height = Screen.height;

m_Width = m_Height * m_Height / Screen.width;

BackGround.sizeDelta = new Vector2 (m_Width, m_Height);

这个可以随意设置。

然后开始截屏了。下面是代码:

Rect m_Rect;

void Start()

{

m_Height = Screen.height;

m_Width = m_Height * m_Height / Screen.width;

BackGround.sizeDelta = new Vector2 (m_Width, m_Height);

m_Rect= new Rect();

Vector3[] fourCornersArray = new Vector3[4];

BackGround.GetWorldCorners (fourCornersArray);

m_Rect.width = fourCornersArray [2].x - fourCornersArray [0].x;

m_Rect.height = fourCornersArray [2].y - fourCornersArray [0].y;

m_Scale = BackGround.sizeDelta.x / m_Rect.width;

m_Rect.width = BackGround.sizeDelta.x;

m_Rect.height = BackGround.sizeDelta.y;

m_Rect.x = Screen.width * 0.5f - m_Rect.width / 2;

m_Rect.y = Screen.height * 0.5f - m_Rect.height / 2;

}

IEnumerator Screenshot()

{

yield return new WaitForEndOfFrame();

BackGround.localScale = new Vector3 (m_Scale, m_Scale, m_Scale);

Texture2D screenShot = new Texture2D((int)m_Rect.width, (int)m_Rect.height, TextureFormat.RGB24,false);

screenShot.ReadPixels(m_Rect, 0, 0);

screenShot.Apply();

byte[] bytes = screenShot.EncodeToPNG();

string filename = Application.persistentDataPath + "/Screenshot.png";

System.IO.File.WriteAllBytes(filename, bytes);

Invoke ("Share", 2f);

}

这样在需要截图的时候调用StartCoroutine (Screenshot());同样地就在Application.persistentDataPath + "/Screenshot.png"; 路径下保存了一份截屏文件。分享时将这种图片分享就可以了。

——Rocky
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: