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.");
}
}
}
unity屏幕截图
最新推荐文章于 2024-07-04 10:10:29 发布