unity屏幕截图

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class xiangjijietu : MonoBehaviour
{
	public Image image;

    // Start is called before the first frame update
    void Start()
    {
		
	}

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
			//截全屏
			CaptureScreenshot(new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f));
			//截部分
			//CaptureScreenshot(new Rect(Screen.width * 0.25f, Screen.height * 0.25f, Screen.width * 0.5f, Screen.height * 0.5f));
		}
    }
	Texture2D screen;
	/// <summary>
	/// Captures the screenshot2.
	/// </summary>
	/// <returns>The screenshot2.</returns>
	/// <param name="rect">Rect.截图的区域,左下角为o点</param>
	void CaptureScreenshot(Rect rect)
	{
		// 先创建一个的空纹理,大小可根据实现需要来设置
		 screen = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);

		StartCoroutine(ie(rect));
	}

	IEnumerator ie(Rect rect)
    {
		//在当前渲染结束后执行
		yield return new WaitForEndOfFrame();
		//读取屏幕像素信息并存储为纹理数据,
		screen.ReadPixels(rect, 0, 0);
		screen.Apply();

		

		//然后将这些纹理数据,成一个png图片文件
		byte[] bytes = screen.EncodeToPNG();
		//将bytes[]转为sprite
		zhuanSprite(bytes);
		//创建保存路径
		string filename = Application.dataPath + "/Screen.png";

		System.IO.File.WriteAllBytes(filename, bytes);
	}

	void zhuanSprite(byte[] imageData)
	{
		//初始大小,稍后会被覆盖 
		Texture2D texture = new Texture2D(2, 2);
		//尝试加载图像 
		bool result = texture.LoadImage(imageData);  

		if (result)
		{
			// 加载成功,现在texture包含了图像数据  
			// 注意:你可能需要设置texture的wrap mode和filter mode  
			texture.wrapMode = TextureWrapMode.Clamp;
			texture.filterMode = FilterMode.Bilinear;

			// 现在可以将Texture2D转换为Sprite了  
			Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

			image.sprite = sprite;

			
		}
		else
		{
			Debug.LogError("Failed to load image from byte array.");
		}
	}
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值