這篇文章主要講解了unity實(shí)現(xiàn)按住鼠標(biāo)選取區(qū)域截圖的方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
創(chuàng)新互聯(lián)公司主營獨(dú)山子網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP軟件開發(fā),獨(dú)山子h5微信平臺(tái)小程序開發(fā)搭建,獨(dú)山子網(wǎng)站營銷推廣歡迎獨(dú)山子等地區(qū)企業(yè)咨詢
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; //重新計(jì)算截取的位置 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ū)域讀取像素;注意是以左下角為原點(diǎn)讀取 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實(shí)現(xiàn)截屏功能的代碼,供大家參考:
public class ScreenShot : MonoBehaviour { void OnScreenShotClick() { //得到當(dāng)前系統(tǒng)時(shí)間 System.DateTime now = System.DateTime.Now; string times = now.ToString(); //去掉前后空格 times = times.Trim(); //將斜杠替換成橫杠 times = times.Replace("/", "-"); string fileName = "ARScreenShot" + times + ".png"; //判斷該平臺(tái)是否為安卓平臺(tái) 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); //應(yīng)用截屏 texture.Apply(); //將對(duì)象序列化 byte[] bytes = texture.EncodeToPNG(); //設(shè)定存儲(chǔ)到的手機(jī)文件夾路徑 string destination = "/sdcard/DCIM/Screenshots"; //如果不存在該文件夾 if (!Directory.Exists(destination)) { //創(chuàng)建該文件夾 Directory.CreateDirectory(destination); } string pathSave = destination + "/" + fileName; File.WriteAllBytes(pathSave, bytes); } } }
看完上述內(nèi)容,是不是對(duì)unity實(shí)現(xiàn)按住鼠標(biāo)選取區(qū)域截圖的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。