Unity截屏(部分屏幕)并显示

在这里插入图片描述
上代码(https://blog.csdn.net/anyuanlzh/article/details/17008909这个链接的总结更为全面)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class MyShot : MonoBehaviour
{
    public Texture2D texture2d;
    public bool isShoot;
    // Start is called before the first frame update
    void Start()
    {
        texture2d = new Texture2D(256,256,TextureFormat.RGB24,false);
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            StartCoroutine(CaptrueScreenShoot()); //得写成延迟,因为必须用到语句yield return new WaitForEndOfFrame();
        }
       
    }
    void OnGUI()
    {
        if(isShoot)
        {
            GUI.DrawTexture(new Rect(0, 0, 100, 100), texture2d, ScaleMode.StretchToFill);//GUI坐标系 坐标原点是屏幕左上角
            //isShoot = false;
        }
    }

    IEnumerator CaptrueScreenShoot()
    {
        //只在每一帧渲染完成后才读取屏幕信息(必须)
        yield return new WaitForEndOfFrame();

        //读取屏幕像素信息并存储为纹理数据
        //texture2d.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);//Texture2D用的是“屏幕坐标系”,坐标原点是屏幕左下角
        texture2d.ReadPixels(new Rect(Screen.width/2-128,Screen.height/2-128,256,256),0,0);//屏幕正中256*256的区域
        texture2d.Apply();

        读取将这些纹理数据,成一个png图片文件
        //byte[] bytes = texture2d.EncodeToPNG();
        //string filename = Application.dataPath + "/" + "Show.png";
        写入文件 
        //File.WriteAllBytes(filename, bytes);
        //设置成可显示
        isShoot = true;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值