unity 框選自由截圖
阿新 • • 發佈:2019-02-11
先上圖看一下,第一張是截出來的圖,第二張,執行圖。
借鑑別人程式碼,組合而成的。。。
廢話不說了,程式碼中的註釋還算詳細
需要說明一下的是,框選的時候填充的有顏色,這樣截圖的時候,填充的顏色也帶進去了。可以把using UnityEngine; using System.Collections; using System.IO; public class draw : MonoBehaviour { public Color rColor = Color.green; private Vector3 start = Vector3.zero; private Vector3 end = Vector3.zero; private Material rMat = null; private bool drawFlag = false; private Rect rect; private Texture2D cutImage; // Use this for initialization void Start () { rMat = new Material( "Shader \"Lines/Colored Blended\" {" + "SubShader { Pass { " + " Blend SrcAlpha OneMinusSrcAlpha " + " ZWrite Off Cull Off Fog { Mode Off } " + " BindChannels {" + " Bind \"vertex\", vertex Bind \"color\", color }" + "} } }" );//生成畫線的材質 rMat.hideFlags = HideFlags.HideAndDontSave; rMat.shader.hideFlags = HideFlags.HideAndDontSave; } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)){ drawFlag = true;//如果滑鼠左鍵按下 設定開始畫線標誌 start = Input.mousePosition;//記錄按下位置 end = Input.mousePosition;//滑鼠當前位置 }else if (Input.GetMouseButtonUp(0)){ drawFlag = false;//如果滑鼠左鍵放開 結束畫線 } if (Input.GetKeyDown (KeyCode.P)) { StartCoroutine(CutImage()); } } //繪製框選 void OnPostRender() {//畫線這種操作推薦在OnPostRender()裡進行 而不是直接放在Update,所以需要標誌來開啟 if(drawFlag){ end = Input.mousePosition;//滑鼠當前位置 } GL.PushMatrix();//儲存攝像機變換矩陣 if (! rMat) return; rMat.SetPass( 0 ); GL.LoadPixelMatrix();//設定用螢幕座標繪圖 GL.Begin(GL.QUADS); GL.Color( new Color(rColor.r,rColor.g,rColor.b,0.1f) );//設定顏色和透明度,方框內部透明 GL.Vertex3( start.x,start.y,0); GL.Vertex3( end.x,start.y,0); GL.Vertex3( end.x,end.y,0 ); GL.Vertex3( start.x,end.y,0 ); GL.End(); GL.Begin(GL.LINES); GL.Color(rColor);//設定方框的邊框顏色 邊框不透明 GL.Vertex3( start.x,start.y,0); GL.Vertex3( end.x,start.y,0); GL.Vertex3( end.x,start.y,0); GL.Vertex3( end.x,end.y,0 ); GL.Vertex3( end.x,end.y,0 ); GL.Vertex3( start.x,end.y,0 ); GL.Vertex3( start.x,end.y,0 ); GL.Vertex3(start.x,start.y,0); GL.End(); GL.PopMatrix();//恢復攝像機投影矩陣 } IEnumerator CutImage() { string date = System.DateTime.Now.ToString("yyyyMMddHHmmss"); //圖片大小 cutImage = new Texture2D((int)(end.x - start.x), (int)(start.y - end.y), TextureFormat.RGB24, true); //座標左下角為0 rect = new Rect((int)start.x, Screen.height - (int)(Screen.height - end.y), (int)(end.x - start.x), (int)(start.y - end.y)); yield return new WaitForEndOfFrame(); cutImage.ReadPixels(rect, 0, 0, true); cutImage.Apply(); yield return cutImage; byte[] byt = cutImage.EncodeToPNG(); //儲存截圖 File.WriteAllBytes(Application.streamingAssetsPath + "/CutImage" +date + ".png", byt); } }
<span style="white-space:pre"> </span>GL.LoadPixelMatrix();//設定用螢幕座標繪圖 GL.Begin(GL.QUADS); GL.Color( new Color(rColor.r,rColor.g,rColor.b,0.1f) );//設定顏色和透明度,方框內部透明 GL.Vertex3( start.x,start.y,0); GL.Vertex3( end.x,start.y,0); GL.Vertex3( end.x,end.y,0 ); GL.Vertex3( start.x,end.y,0 ); GL.End();
這段去掉,或者
GL.Color( new Color(rColor.r,rColor.g,rColor.b,0.1f) );
的值改成0全透明