Unity截圖(截指定區域或者是自定義區域)
阿新 • • 發佈:2019-02-01
在unity3d中可能會遇到截圖然後儲存到材質中作為某種顯示使用,網上的程式碼基本都是截圖是的截圖。今天介紹一種截指定區域或者自定義區域的方法。
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
public class TakePhoto : MonoBehaviour
{
public static TakePhoto _Instance;
// 拍照擷取的區域
[Tooltip("拍照擷取的區域")]
public Image im;
//用於控制指定區域的左上點和右下點,並且他們的錨點分別在左上和右下
public Image zuodingIma, xiaIma;
//展示拍照的RawImage
public RawImage[] tx;
public RawImage showTx;
int capx = 0;
int capy = 0;
int capwidth = 0;
int capheight = 0;
int index = 0;
Texture2D t;
private void Awake()
{
_Instance = this;
}
/// <summary>
/// 將截圖區域的Pivot設定為左下角,即 0 0,thisIm是具體的截圖區域
/// </summary>
void SetPivot(Image thisIm)
{
thisIm.GetComponent<RectTransform>().pivot = new Vector2(0, 0);
}
public void Shoot()
{
AudioController.instance.PlayFX("shoot" );
StartCoroutine(GetScreenTexture());
}
/// <summary>
/// 截指定區域圖並賦值給材質
/// </summary>
/// <returns></returns>
IEnumerator GetScreenTexture()
{
capx = Mathf.Abs((int)im.gameObject.transform.position.x);
capy = Mathf.Abs((int)im.gameObject.transform.position.y);
capwidth = Mathf.Abs((int)(xiaIma.gameObject.transform.position.x - im.gameObject.transform.position.x)) ;
capheight = Mathf.Abs((int)(zuodingIma.gameObject.transform.position.y - im.gameObject.transform.position.y)) ;
yield return new WaitForEndOfFrame();
t = new Texture2D(capwidth, capheight, TextureFormat.RGB24, false);//需要正確設定好圖片儲存格式
t.ReadPixels(new Rect(capx, capy, capwidth, capheight), 0, 0, false);//按照設定區域讀取畫素;注意是以左下角為原點讀取
t.Compress(false);
t.Apply();
//二進位制轉換,儲存到手機
// byte[] byt = t.EncodeToPNG();
// File.WriteAllBytes(Application.dataPath + this.index + ".png", byt);
}
/// <summary>
///截圖不滿意重拍
/// </summary>
public void ReShootPhoto()
{
//重拍
}
/// <summary>
/// 繼續拍照
/// </summary>
public void ContinueShoot()
{
}
public string deviceName;
WebCamTexture tex;//接收返回的圖片資料
IEnumerator Camera()
{
// yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授權
int height = Screen.height;
int width = Screen.width;
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName = devices[0].name;
//設定攝像機攝像的區域
tex = new WebCamTexture(deviceName, width, height, 40);
tex.Play();//開始攝像
}
yield return new WaitForSeconds(0.1f);
}
}