您好,登錄后才能下訂單哦!
這篇文章主要講解了unity實現(xiàn)按住鼠標選取區(qū)域截圖的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
private int capBeginX; private int capBeginY; private int capFinishX; private int capFinishY; public Image showImg; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown (0)) { Vector3 mousePos = Input.mousePosition; Vector2 beginPos = new Vector2 (mousePos.x, mousePos.y); capBeginX = (int)mousePos.x; capBeginY = (int)mousePos.y; } if (Input.GetMouseButtonUp (0)) { Vector3 mousePos = Input.mousePosition; Vector2 finishPos = new Vector2 (mousePos.x, mousePos.y); capFinishX = (int)mousePos.x; capFinishY = (int)mousePos.y; //重新計算截取的位置 int capLeftX = (capBeginX < capFinishX) ? capBeginX : capFinishX; int capRightX = (capBeginX < capFinishX) ? capFinishX : capBeginX; int capLeftY = (capBeginY < capFinishY) ? capBeginY : capFinishY; int capRightY = (capBeginY < capFinishY) ? capFinishY : capBeginY; Rect rect=new Rect(capLeftX,capLeftY,capRightX,capRightY); StartCoroutine( Captrue (rect)); } } IEnumerator Captrue(Rect rect){ int t_width = Mathf.Abs (capFinishX - capBeginX); int t_length = Mathf.Abs (capFinishY - capBeginY); yield return new WaitForEndOfFrame (); Texture2D t = new Texture2D(t_width , t_length,TextureFormat.RGB24, true);//需要 正確設(shè)置好圖片保存格式 t.ReadPixels(rect, 0, 0, false);//按照設(shè)定區(qū)域讀取像素;注意是以左下角為原點讀取 t.Apply(); byte[] byt = t.EncodeToPNG(); File.WriteAllBytes(Application.dataPath + Time.time + ".png", byt); Sprite target = Sprite.Create (t, new Rect(0, 0, t_width, t_length), Vector2.zer); showImg.sprite = target; }
小編為大家分享一段Unity實現(xiàn)截屏功能的代碼,供大家參考:
public class ScreenShot : MonoBehaviour { void OnScreenShotClick() { //得到當前系統(tǒng)時間 System.DateTime now = System.DateTime.Now; string times = now.ToString(); //去掉前后空格 times = times.Trim(); //將斜杠替換成橫杠 times = times.Replace("/", "-"); string fileName = "ARScreenShot" + times + ".png"; //判斷該平臺是否為安卓平臺 if (Application.platform == RuntimePlatform.Android) { //參數(shù)依次為 屏幕寬度 屏幕高度 紋理格式 是否使用映射 Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //讀取貼圖 texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); //應用截屏 texture.Apply(); //將對象序列化 byte[] bytes = texture.EncodeToPNG(); //設(shè)定存儲到的手機文件夾路徑 string destination = "/sdcard/DCIM/Screenshots"; //如果不存在該文件夾 if (!Directory.Exists(destination)) { //創(chuàng)建該文件夾 Directory.CreateDirectory(destination); } string pathSave = destination + "/" + fileName; File.WriteAllBytes(pathSave, bytes); } } }
看完上述內(nèi)容,是不是對unity實現(xiàn)按住鼠標選取區(qū)域截圖的方法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。