成都创新互联网站制作重庆分公司

Unity如何在任意区域截屏创建Sprite

这篇文章主要介绍Unity如何在任意区域截屏创建Sprite,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

公司专注于为企业提供成都网站建设、网站建设、微信公众号开发、商城网站制作,小程序设计,软件定制网站开发等一站式互联网企业服务。凭借多年丰富的经验,我们会仔细了解各客户的需求而做出多方面的分析、设计、整合,为客户设计出具风格及创意性的商业解决方案,创新互联更提供一系列网站制作和网站推广的服务。

Unity截取全屏静帧的方法较为简单这里不作讨论,指定区域截图用到的最主要的方法就是读取屏幕像素:

//        // 摘要:        //     Read pixels from screen into the saved texture data.        //        // 参数:        //   source:        //     Rectangular region of the view to read from. Pixels are read from current render        //     target.        //        //   destX:        //     Horizontal pixel position in the texture to place the pixels that are read.        //        //   destY:        //     Vertical pixel position in the texture to place the pixels that are read.        //        //   recalculateMipMaps:        //     Should the texture's mipmaps be recalculated after reading?        public void ReadPixels(Rect source, int destX, int destY, [DefaultValue("true")] bool recalculateMipMaps);        [ExcludeFromDocs]        public void ReadPixels(Rect source, int destX, int destY);

为了方便调用,写一个扩展协程如下:

public static IEnumerator CutSpriteFromScreen(this RectTransform boxMin, RectTransform boxMax, UnityAction complete)    {        var sp = new Vector2(boxMin.position.x, boxMin.position.y);        var temp = new Vector2(boxMax.position.x, boxMax.position.y);        Vector2Int size = new Vector2Int((int)(temp.x - sp.x), (int)(temp.y - sp.y));
       //判断截图框是否超出屏幕边界        if (sp.x < 0 || sp.y < 0 || sp.x + size.x > Screen.width || sp.y + size.y > Screen.height)            yield break;
       //等待当前帧渲染结束,此为必须项        yield return new WaitForEndOfFrame();
       Texture2D texture = new Texture2D(size.x, size.y, TextureFormat.RGB24, false);
       texture.ReadPixels(new Rect(sp.x, sp.y, size.x, size.y), 0, 0, false);        texture.Apply();
       complete(Sprite.Create(texture, new Rect(Vector2Int.zero, size), Vector2.one * .5f));    }

调用如下:

StartCoroutine(BoxMin.CutSpriteFromScreen(BoxMax, (x) => GameData.Instance.PlayerData.Bag.FragCutIcon = x));

效果展示:

Unity如何在任意区域截屏创建Sprite

Unity如何在任意区域截屏创建Sprite

可以直接将拼好的芯片图截取后保存起来方便在其他界面展示安装效果,省去了每一界面都划格子重新读取数据计算一遍;

因为事实上只有在设置芯片的页面才需要单独对每块芯片进行细致操作,其他位置可以简化为展示一张缩略图;

当芯片的安装发生变化时,同步更新该缩略图即可。

以上是“Unity如何在任意区域截屏创建Sprite”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


当前名称:Unity如何在任意区域截屏创建Sprite
网页地址:http://cxhlcq.com/article/jopiio.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部