效果:
代碼如下:
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using NPinyin;
using System.IO;
public class NewBehaviourScript : MonoBehaviour {
//截屏結束的位置
private Vector3 e_pos;
//是否繪製
private bool isDraw;
//繪製狀態
private bool stateDraw;
//開始繪製
private bool stateDrawStart;
//截屏開始的位置
private Vector3 s_pos;
Rect rect;
public Material lineMaterial;
private void Update()
{
if (stateDraw == true)
{
//按下鼠標左鍵時,記錄當前鼠標的位置爲開始截屏時的位置
if (Input.GetMouseButtonDown(0))
{
stateDrawStart = true;
s_pos = Input.mousePosition;
}
//鼠標處於按下狀態時
if (Input.GetMouseButton(0))
{
e_pos = Input.mousePosition;
//可以開始繪製
isDraw = true;
}
//擡起鼠標左鍵時,記錄當前鼠標的位置爲結束截屏時的位置
if (Input.GetMouseButtonUp(0) && stateDrawStart == true)
{
//結束繪製
isDraw = false;
e_pos = Input.mousePosition;
//獲取到截屏框起始點的位置,和寬高。
rect = new Rect(Mathf.Min(s_pos.x, e_pos.x), Mathf.Min(s_pos.y, e_pos.y), Mathf.Abs(s_pos.x - e_pos.x), Mathf.Abs(s_pos.y - e_pos.y));
//開啓繪製的協程方法
StartCoroutine(Capsture(rect));
stateDraw = false;
stateDrawStart = false;
}
}
}
/// <summary>
/// 保存截圖
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
IEnumerator Capsture(Rect rect)
{
yield return new WaitForEndOfFrame();
//創建紋理(紋理貼圖的大小和截屏的大小相同)
Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
//讀取像素點
tex.ReadPixels(rect, 0, 0);
//將像素點應用到紋理上,繪製圖片
tex.Apply();
//將圖片裝換成jpg的二進制格式,保存在byte數組中(計算機是以二進制的方式存儲數據)
byte[] result = tex.EncodeToPNG();
//文件夾(如果StreamAssets文件夾不存在,在Assets文件下創建該文件夾)
if (!Directory.Exists(Application.streamingAssetsPath))
Directory.CreateDirectory(Application.streamingAssetsPath);
//將截屏圖片存儲到本地
string filename = Application.dataPath + "/StreamingAssets/Screenshot.png";
File.WriteAllBytes(filename, result);
}
/// <summary>
/// 用GL畫線
/// </summary>
void OnPostRender()
{
if (!isDraw) return;
//print(s_pos);
Vector3 sPos = Camera.main.ScreenToWorldPoint(s_pos + new Vector3(0, 0, 10));
Vector3 ePos = Camera.main.ScreenToWorldPoint(e_pos + new Vector3(0, 0, 10));
//print(string.Format("GL.....{0}, {1}", sPos, ePos));
// Set your materials Done
GL.PushMatrix();
// yourMaterial.SetPass( );
lineMaterial.SetPass(0);//告訴GL使用該材質繪製
// Draw your stuff
//始終在最前面繪製
GL.invertCulling = true;
GL.Begin(GL.LINES);//開始繪製
//GL.Vertex(sPos);
//GL.Vertex(ePos);
//如果想要繪製,矩形,將下面代碼啓動
GL.Vertex(sPos);
GL.Vertex(new Vector3(ePos.x, sPos.y, 0));
GL.Vertex(new Vector3(ePos.x, sPos.y, 0));
GL.Vertex(ePos);
GL.Vertex(ePos);
GL.Vertex(new Vector3(sPos.x, ePos.y, 0));
GL.Vertex(new Vector3(sPos.x, ePos.y, 0));
GL.Vertex(sPos);
GL.End();//結束繪製
GL.PopMatrix();
}
public void OnBtnClick() {
stateDraw = true;
}
}