Unity使用Rect类进行截屏

关于截屏有很多种截取全屏的方法,但是想要截取Game视图中的部分区域,可以使用Rect和ReadPixels进行截取。如下图所示,是需要截取的部分。

浅蓝色是Game视图,即全屏幕尺寸,红色区域是基于Canvas左上角对齐,红色区域右边距离屏幕边界610px,下面距离屏幕边界70px,蓝色区域是红色区域的子级图片,上下左右居中对齐,现在要截取蓝色区域的图片导出。

1.可以先创建一个Rect得到要截取的矩形区域,Rect rect = new Rect(float x, float y, float width, float height);

该方法先在屏幕上获取一个坐标点,以及长和宽来确定一个举行区域。

2.然后:Texture2D screenShot= new Texture2D(int width, int height, TextureFormat format, bool mipmap)

即创建纹理,纹理的宽和高,格式,是否为位图。

3. screenShot.ReadPixels(Rext rect, int destX, int destY, bool recalculateMipmaps)

4.screenShot.Apply();

5.System.IO.File.WriteAllBytes("D://xxxxx/xxx/" + picName, bytes);

6.System.IO.File.WriteAllBytes(Live3DApplication.Instance.config.poserEditorImgPath(false) + picName, bytes);

//background为深蓝色区域UI的GameObject, x, y为Rect的坐标值
            float x = (Screen.width - 610) / 2 - background.GetComponent<RectTransform>().rect.width / 2;
            float y = (Screen.height - 70) / 2 + 70 - background.GetComponent<RectTransform>().rect.height / 2;
//计算得到x和y后,计算Rect,创建大小为background宽和高的Rect           
            Rect rect = new Rect(x, y, background.GetComponent<RectTransform>().rect.width, background.GetComponent<RectTransform>().rect.height);
//创建Rect大小的纹理
            Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
            yield return new WaitForEndOfFrame();
            screenShot.ReadPixels(rect, 0, 0, false);
            screenShot.Apply();
            byte[] bytes = screenShot.EncodeToPNG();
            if (poserType == PoserType.Export) {
                System.IO.File.WriteAllBytes(Config.outputFile + picName, bytes);
            }
            System.IO.File.WriteAllBytes(Config.poserEditorImgPath(false) + picName, bytes);

最终截取的图片如下:

经验分享 程序员 微信小程序 职场和发展