Unity中的截图功能

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

public class ScreenShot : MonoBehaviour
{
    public Rect rect = new Rect(700, 500, 300, 300);
    public string serverFilePath = "";
    private string fileName;
    //public Camera camera;
    //RenderTexture rt;
    // Start is called before the first frame update
    void Start()
    {
        //rt = new RenderTexture(1920, 1080, 0);
        //camera.targetTexture = rt;
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void JieTu()
    {
        string name = "CarID-" + Data._instance.carID + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
        fileName = GameInfo._instance.pictureFileNameByDate + "/" + name + ".png";
        //fileName = @"D:\Shot" + "/" + name + ".png";
        //fileName = DateTime.Now.ToFileTime().ToString() + "_" + Data._instance.carID + "_";
        //fileName = @"\\192.168.10.10\Playback" + "/" + fileName + "Screenshot.png";

        serverFilePath = fileName.Replace("\\", "/");

        //开启截屏
        StartCoroutine(Beginshot());
    }

    IEnumerator Beginshot()
    {
        yield return new WaitForEndOfFrame();
        CaptureScreenshot2(rect);
        StopCoroutine("Beginshot");
    }

    /// <summary>
    /// Captures the screenshot2.
    /// </summary>
    /// <returns>The screenshot2.</returns>
    /// <param name="rect">Rect.截图的区域,左下角为o点</param>
    Texture2D CaptureScreenshot2(Rect rect)
    {
        //RenderTexture.active = rt;
        //Rect rect2 = new Rect(rect.x + 960f, rect.y + 540f, rect.width, rect.height);
        //print("图片长" + rect.width + "图片宽" + rect.height + "++" + rect.x + "++" + rect.y);
        //先创建一个的空纹理,大小可根据实现需要来设置
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
#pragma warning disable UNT0017 // SetPixels invocation is slow
        screenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
#pragma warning restore UNT0017 // SetPixels invocation is slow
        screenShot.Apply();
        //RenderTexture.active = null;
        //fileName = @"D:\Shot";
        byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件
        System.IO.File.WriteAllBytes(fileName, bytes);
        Debug.Log(string.Format("截屏了一张图片: {0}", fileName));
        //最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。
        return screenShot;
    }
}
 

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值