Unity3D -- 自定义范围截屏

大家都知道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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值