Unity 任意区域截屏创建Sprite
Unity截取全屏静帧的方法较为简单这里不作讨论,指定区域截图用到的最主要的方法就是读取屏幕像素:
1 // 2 // 摘要: 3 // Read pixels from screen into the saved texture data. 4 // 5 // 参数: 6 // source: 7 // Rectangular region of the view to read from. Pixels are read from current render 8 // target. 9 // 10 // destX: 11 // Horizontal pixel position in the texture to place the pixels that are read. 12 // 13 // destY: 14 // Vertical pixel position in the texture to place the pixels that are read. 15 // 16 // recalculateMipMaps: 17 // Should the texture's mipmaps be recalculated after reading? 18 public void ReadPixels(Rect source, int destX, int destY, [DefaultValue("true")] bool recalculateMipMaps); 19 [ExcludeFromDocs] 20 public void ReadPixels(Rect source, int destX, int destY);
为了方便调用,写一个扩展协程如下:
1 public static IEnumerator CutSpriteFromScreen(this RectTransform boxMin, RectTransform boxMax, UnityAction<Sprite> complete) 2 { 3 var sp = new Vector2(boxMin.position.x, boxMin.position.y); 4 var temp = new Vector2(boxMax.position.x, boxMax.position.y); 5 Vector2Int size = new Vector2Int((int)(temp.x - sp.x), (int)(temp.y - sp.y)); 6 7 //判断截图框是否超出屏幕边界 8 if (sp.x < 0 || sp.y < 0 || sp.x + size.x > Screen.width || sp.y + size.y > Screen.height) 9 yield break; 10 11 //等待当前帧渲染结束,此为必须项 12 yield return new WaitForEndOfFrame(); 13 14 Texture2D texture = new Texture2D(size.x, size.y, TextureFormat.RGB24, false); 15 16 texture.ReadPixels(new Rect(sp.x, sp.y, size.x, size.y), 0, 0, false); 17 texture.Apply(); 18 19 complete(Sprite.Create(texture, new Rect(Vector2Int.zero, size), Vector2.one * .5f)); 20 }
调用如下:
1 StartCoroutine(BoxMin.CutSpriteFromScreen(BoxMax, (x) => GameData.Instance.PlayerData.Bag.FragCutIcon = x));
效果展示:
可以直接将拼好的芯片图截取后保存起来方便在其他界面展示安装效果,省去了每一界面都划格子重新读取数据计算一遍;
因为事实上只有在设置芯片的页面才需要单独对每块芯片进行细致操作,其他位置可以简化为展示一张缩略图;
当芯片的安装发生变化时,同步更新该缩略图即可。
关于芯片拼图的算法可以详细见之前写过的另一篇随笔: