截屏脚本

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

public class printScreen : MonoBehaviour {
    private Texture2D screenShot;
    private bool shoot = false;
	void Start () {
        screenShot = new Texture2D(256, 256, TextureFormat.RGB24, false);
	}
	void Update () {
        if (Input.GetKeyUp(KeyCode.Mouse0)) {
            StartCoroutine(CaptureScreenshot());
        }
	}
    void OnGUI() {
        if (shoot) {
            GUI.DrawTexture(new Rect(10, 10, 256, 256), 
                screenShot, ScaleMode.StretchToFill);
        }
    }
    IEnumerator CaptureScreenshot() {
        yield return new WaitForEndOfFrame();

        screenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        screenShot.Apply();

        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/" + Time.time.ToString() + ".png";
        Debug.Log(Application.dataPath);
        File.WriteAllBytes(filename, bytes);
        shoot = true;
    }
}

小测试:在场景里随便添加几个方块,然后把脚本挂在相机上,运行场景

截图的位置是从屏幕的左下角开始的,如果想从中心截屏,把 ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0) 改为 ReadPixels(new Rect(Screen.width*0.5f,Screen.height*0.5f,256,256),0,0) 然后就可以了。

ReadPixels函数中的第一个参数理解为:读取的屏幕像素矩形区域是以game视窗的左下角为原点的矩形区域。第二、第三个参数是:位移参数一的偏移量,向左或向右,向上或向下 偏移。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值