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));
效果展示:
可以直接將拼好的晶片圖擷取後儲存起來方便在其他介面展示安裝效果,省去了每一介面都劃格子重新讀取資料計算一遍;
因為事實上只有在設定晶片的頁面才需要單獨對每塊晶片進行細緻操作,其他位置可以簡化為展示一張縮圖;
當晶片的安裝發生變化時,同步更新該縮圖即可。
關於晶片拼圖的演算法可以詳細見之前寫過的另一篇隨筆: