Unity 截屏并显示在Image上

参考文章:【Unity】Unity中通过纹理截屏将图片保存到本地_Zok93-CSDN博客 

方法一:截取全屏 

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LXTest : MonoBehaviour
{    
    Texture2D screenShot;//保存截取的纹理
    public Transform tra;//显示截屏的3D对象
    public Image image;  //显示截屏的Image
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartCoroutine(ScrrenCapture(new Rect(0, 0, Screen.width, Screen.height)));
        }
    }

    IEnumerator ScrrenCapture(Rect rect)
    {
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        yield return new WaitForEndOfFrame();
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();
        Sprite sp = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f), 100.0f);
        image.sprite = sp;
       // tra.GetComponent<MeshRenderer>().material.mainTexture = screenShot;
    }
}

方法二:根据区域进行截屏

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LXCatchScreenImage : MonoBehaviour
{
	public Image TargetImage;//想要截取的目标区域
	public Image ShowImage;  //截取后用来显示的Iamge
	Texture2D screenShot;    //存储截取的纹理
	private void Update()
	{
		if (Input.GetMouseButtonDown(0))
		{
			StartCoroutine(CaptureGUIPNG());
		}
	}
	// 定义一个协程
	IEnumerator CaptureGUIPNG()
	{
		// 因为"WaitForEndOfFrame"在OnGUI之后执行
		// 所以我们只在渲染完成之后才读取屏幕上的画面
		yield return new WaitForEndOfFrame();
		var rect = TargetImage.GetComponent<RectTransform>();
		int width = (int)rect.sizeDelta.x;
		int height = (int)rect.sizeDelta.y;
		var startx = rect.position.x - (width / 2) * rect.localScale.x;
		var starty = rect.position.y - (height / 2) * rect.localScale.y;
		if (startx + width > Screen.width)
			width = (int)Mathf.Floor(Screen.width - startx);
		if (starty + height > Screen.height)
			height = (int)Mathf.Floor(Screen.height - starty);
		// 创建一个屏幕大小的纹理,RGB24 位格(24位格没有透明通道,32位的有)
		screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
		// 读取屏幕内容到我们自定义的纹理图片中
		screenShot.ReadPixels(new Rect(startx, starty, width, height), 0, 0);
		// 保存前面对纹理的修改
		screenShot.Apply();
		// 编码纹理为PNG格式
		//byte[] bytes = screenShot.EncodeToPNG();
		// 销毁无用的图片纹理
		//Destroy(tex);
		Sprite sp = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f), 100.0f);
		ShowImage.sprite = sp;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值