发布时间:2018-02-09责任编辑:朱明 浏览:2238
发现很多朋友对使用u3d来实现截图比较生疏,我这里把我从网上学习到的截图方法分享给大家供大家使用参考。
采用的是new Texture2D来截取图片分为截取一部分和全屏; //截取一块区域,通过鼠标点击的点来获取要截取的区域。
using UnityEngine;
using System.Collections;
using System.IO;
public class ShotScreenPicture : MonoBehaviour
{
Texture2D image;
Texture2D cutImage;
WWW www;
Rect rect;
float time;
Vector2 pos1;
Vector2 pos2;
// Update is called once per frame
void Update()
{
//点击鼠标左键,记录第一个位置
if (Input.GetMouseButtonDown(0))
{
pos1 = Input.mousePosition;
time = Time.time;
if (time > 1f)
{
Debug.Log(pos1);
}
}
//放开左键记录第二个位置
if (Input.GetMouseButtonUp(0))
{
pos2 = Input.mousePosition;
Debug.Log(pos2);
StartCoroutine(CutImage());
time = 0;
}
}
void OnGUI()
{
//当下载完成
if (www.isDone)
{
GUI.DrawTexture(new Rect(0, 0, 600, 904), image);
}
GUI.Button(new Rect(0, 0, 100, 50), "W" + Screen.width + "H" + Screen.height);
if (pos1 != null)
{
GUI.Button(new Rect(0, 50, 150, 50), pos1.ToString());
}
if (pos2 != null)
{
GUI.Button(new Rect(0, 100, 150, 50), pos2.ToString());
}
if (cutImage != null)
{
GUI.Button(new Rect(0, 150, 150, 50), "image W" + cutImage.width + "H" + cutImage.height);
}
if (rect != null)
{
GUI.Button(new Rect(0, 200, 250, 50), rect.ToString());
}
}
//截图
IEnumerator CutImage()
{
//图片大小
cutImage = new Texture2D((int)(pos2.x - pos1.x), (int)(pos1.y - pos2.y), TextureFormat.RGB24, true);
//坐标左下角为0
rect = new Rect((int)pos1.x, Screen.height - (int)(Screen.height - pos2.y), (int)(pos2.x - pos1.x), (int)(pos1.y - pos2.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.png", byt);
}
}
//全屏截图
//存储路径
private string Path_save;
//读取路径
private string Path_read;
private string filepath;
private string destination;
void Start()
{
filepath = Application.persistentDataPath + "/test.txt";
}
public void OnClickShot()
{
StartCoroutine(getTexture2d());
}
IEnumerator getTexture2d()
{
//隐藏UI
.................................
//截图操作
yield return new WaitForSeconds(0.1f);
Texture2D t = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
//显示UI