unity實現按住滑鼠選取區域截圖
阿新 • • 發佈:2020-04-17
本文例項為大家分享了unity按住滑鼠選取區域截圖的具體程式碼,供大家參考,具體內容如下
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);//需要 正確設定好圖片儲存格式 t.ReadPixels(rect,false);//按照設定區域讀取畫素;注意是以左下角為原點讀取 t.Apply(); byte[] byt = t.EncodeToPNG(); File.WriteAllBytes(Application.dataPath + Time.time + ".png",byt); Sprite target = Sprite.Create (t,new Rect(0,t_width,t_length),Vector2.zer); showImg.sprite = target; }
小編為大家分享一段Unity實現截圖功能的程式碼,供大家參考:
public class ScreenShot : MonoBehaviour { void OnScreenShotClick() { //得到當前系統時間 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) { //引數依次為 螢幕寬度 螢幕高度 紋理格式 是否使用對映 Texture2D texture = new Texture2D(Screen.width,Screen.height,false); //讀取貼圖 texture.ReadPixels(new Rect(0,Screen.width,Screen.height),0); //應用截圖 texture.Apply(); //將物件序列化 byte[] bytes = texture.EncodeToPNG(); //設定儲存到的手機資料夾路徑 string destination = "/sdcard/DCIM/Screenshots"; //如果不存在該資料夾 if (!Directory.Exists(destination)) { //建立該資料夾 Directory.CreateDirectory(destination); } string pathSave = destination + "/" + fileName; File.WriteAllBytes(pathSave,bytes); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。