Unity截屏方法,在Unity中进行截屏。

今天我们讨论下Unity3D的截屏方法,总共有三种方式。

1、利用Unity自带的系统方式进行截屏:
Application.CaptureScreenshot("Screenshot.png");

2、利用Texture2D.ReadPixels()方法和Texture2D.EncodeToPng()方法进行截屏并保存数据,代码如下:

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


public class example : MonoBehaviour {
    void Start() {
        UploadPNG();
    }
    //开启一个携程进行截屏
    IEnumerator UploadPNG() 
{
//等待帧结束
yield return new WaitForEndOfFrame();
//获取到屏幕的宽高,进行全屏截图
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
//将图片转成byte数据
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
//利用post方法将图片数据进行上传
WWWForm form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddBinaryData("fileUpload", bytes);
WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form);
yield return w;
if (w.error != null)
print(w.error);
else
print("Finished Uploading Screenshot");
}
}

3、针对某个相机进行截图,代码如下所示:

Texture2D CaptureCamera(Camera camera, Rect rect)   
{  
    // 创建一个RenderTexture对象  
    RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);  
    // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
    camera.targetTexture = rt;  
    camera.Render();  
    //如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。  
//camera2.targetTexture = rt;  
//camera2.Render();   

    // 激活这个rt, 并从中中读取像素。  
    RenderTexture.active = rt;  
    Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false);  
    screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
    screenShot.Apply();  

    // 重置相关参数,以使用camera继续在屏幕上显示  
    camera.targetTexture = null;  
//camera2.targetTexture = null;  
    RenderTexture.active = null; // JC: added to avoid errors  
    GameObject.Destroy(rt);  
    // 最后将这些纹理数据,成一个png图片文件  
    byte[] bytes = screenShot.EncodeToPNG();  
    string filename = Application.dataPath + "/Screenshot.png";  
    System.IO.File.WriteAllBytes(filename, bytes);  
    Debug.Log(string.Format("截屏了一张照片: {0}", filename));  

    return screenShot;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值