您好,登錄后才能下訂單哦!
這篇文章主要介紹Unity如何在任意區(qū)域截屏創(chuàng)建Sprite,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
Unity截取全屏靜幀的方法較為簡(jiǎn)單這里不作討論,指定區(qū)域截圖用到的最主要的方法就是讀取屏幕像素:
// // 摘要: // Read pixels from screen into the saved texture data. // // 參數(shù): // 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);
為了方便調(diào)用,寫一個(gè)擴(kuò)展協(xié)程如下:
public static IEnumerator CutSpriteFromScreen(this RectTransform boxMin, RectTransform boxMax, UnityAction<Sprite> 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;
//等待當(dāng)前幀渲染結(jié)束,此為必須項(xiàng)
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));
}
調(diào)用如下:
StartCoroutine(BoxMin.CutSpriteFromScreen(BoxMax, (x) => GameData.Instance.PlayerData.Bag.FragCutIcon = x));
效果展示:
可以直接將拼好的芯片圖截取后保存起來(lái)方便在其他界面展示安裝效果,省去了每一界面都劃格子重新讀取數(shù)據(jù)計(jì)算一遍;
因?yàn)槭聦?shí)上只有在設(shè)置芯片的頁(yè)面才需要單獨(dú)對(duì)每塊芯片進(jìn)行細(xì)致操作,其他位置可以簡(jiǎn)化為展示一張縮略圖;
當(dāng)芯片的安裝發(fā)生變化時(shí),同步更新該縮略圖即可。
以上是“Unity如何在任意區(qū)域截屏創(chuàng)建Sprite”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。