您的位置:首页 > 移动开发 > Unity3D

Unity中通过纹理截屏将图片保存到本地

2015-09-17 15:13 573 查看
using UnityEngine;
using System.Collections;
using System.IO;

public class SavedScreen : MonoBehaviour {

	
	void Start () {
		// 开启一个协程
		StartCoroutine (UploadPNG());
	}
	

	// 定义一个协程
	IEnumerator UploadPNG () {
		

		// 因为"WaitForEndOfFrame"在OnGUI之后执行
		// 所以我们只在渲染完成之后才读取屏幕上的画面
		yield return new WaitForEndOfFrame();

		int width = Screen.width;
		int height = Screen.height;
		// 创建一个屏幕大小的纹理,RGB24 位格(24位格没有透明通道,32位的有)
		Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);

		// 读取屏幕内容到我们自定义的纹理图片中
		tex.ReadPixels (new Rect(0, 0, width, height), 0, 0);
		// 保存前面对纹理的修改
		tex.Apply ();

		// 编码纹理为PNG格式
		byte[] bytes = tex.EncodeToPNG();
		// 销毁吴永的图片纹理
		Destroy (tex);

		// 将字节保存成图片,这个路径只能在PC端对图片进行读写操作
		File.WriteAllBytes(Application.dataPath + "/onPcSavedScreen.png", bytes);
		// 这个路径会将图片保存到手机的沙盒中,这样就可以在手机上对其进行读写操作了
		File.WriteAllBytes(Application.persistentDataPath + "/onMobileSavedScreen.png", bytes);

	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: