unity截屏功能

unity 截屏方式有很多种
我列几种我用过的方式

一、(说明待完善)全屏截图

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

public class FrameAnimation : MonoBehaviour
{
    public Texture2D image;
    public int w;
    public int h;
    public float nextTime = 0.0f;
    public float rate = 0.3f;
    int i = 0;
    // Use this for initialization
    void Start()
    {
        w = Screen.width;
        h = Screen.height;
        image = new Texture2D(w, h);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0) && Time.time > nextTime)
        {
            nextTime = Time.time + rate;
            i++;
            StartCoroutine(SaveImage(i));
        }
    }

    IEnumerator SaveImage(int i)
    {
        yield return new WaitForEndOfFrame();
        image.ReadPixels(new Rect(0, 0, w, h), 0, 0, true);//read pixels from screen to texture
        image.Apply();
        byte[] bytes = image.EncodeToPNG();
        File.WriteAllBytes(Application.streamingAssetsPath + "/" + i + ".png", bytes);
        Debug.Log("write a pic");
        yield return null;
    }
}

二、

选区截屏,Area所包含的区域就是被截取像素的区域
完整脚本,可直接套用

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

public delegate void FinishEvent(Texture2D texture, string savePath);

public class SavePicture : MonoBehaviour
{
    public Camera cam;//场景相机
    public RectTransform Canvas;//canvas
    public RectTransform Area;//用来取景的ui,设置为透明的

    public FinishEvent Finish;

    public String photoPath;//保存图片的路径
    //public CreatQRCode CreatCode;

    // Take a screen shot immedi
    void Start()
    {
        photoPath = "D:/PicTest/";
        Area.SetParent(Canvas);

        if (Area.anchorMax != Vector2.zero || Area.anchorMin != Vector2.zero || Area.pivot != Vector2.zero)
        {
            Debug.LogError("请将 Anchors 和 Pivot设置为 0");
        }
    }

    void Update()
    {
        //if (Input.GetKeyDown(SaveKey))
        //{
        //    Save();
        //}
    }

    public void Save()
    {
        StartCoroutine(SavePNG());
    }
    //Texture2D tex = null;
    IEnumerator SavePNG()
    {
        //tex = null;//清空

        yield return new WaitForEndOfFrame();

        Vector3 startPos = cam.ViewportToScreenPoint(new Vector2(Area.anchoredPosition3D.x / Canvas.sizeDelta.x, Area.anchoredPosition3D.y / Canvas.sizeDelta.y));
        Vector2 top = new Vector2(Area.anchoredPosition3D.x, Area.anchoredPosition3D.y) + Area.sizeDelta;
        Vector3 endPos = cam.ViewportToScreenPoint(new Vector2(top.x / Canvas.sizeDelta.x, top.y / Canvas.sizeDelta.y));

        int width = (int)(endPos.x - startPos.x);
        int height = (int)(endPos.y - startPos.y);
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        tex.ReadPixels(new Rect(startPos.x, startPos.y, width, height), 0, 0);
        tex.Apply();
        string texName = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".png";
        tex.name = texName;

        byte[] bytes = tex.EncodeToPNG();

        //上传到服务器
        //WWWForm newForm = new WWWForm();

        //string id = "Photo_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");
        //newForm.AddField("id", id);
        //newForm.AddBinaryData("Photo", bytes, "photo.jpg");
        //WWW w = new WWW("http://122.152.206.226:8090/Default.aspx", newForm);
        //while (!w.isDone) { yield return new WaitForEndOfFrame(); }
        //if (w.error == null)
        //{
        //    //Debug.Log(w.text);

        //    //Debug.Log("上传成功");
        //}
        //else
        //{
        //    Debug.LogError(w.error);
        //}
        //string url = "http://122.152.206.226:8090" + @"\Photos" + "/" + id + ".png";
        //CreatCode.Creat(url);//生成二维码

        //本地存储照片
        if (tex == null)
            yield return null;
        //string fullDirPath = Path.GetFullPath(Path.Combine(Application.dataPath, "..")) + @"\Resources\Photos\";
        string path = photoPath + @"\" + texName;
        //Debug.Log("Save Pic:" + path);

        if (PrintImage.Instances != null)//传递要打印的照片的路径
            PrintImage.Instances.filePicPath = path;
        //if (PhotoWallInterface.Instance != null)
        //    PhotoWallInterface.Instance.SetNewPhotos(tex);//显示新的照片

        System.IO.File.WriteAllBytes(path, bytes);

        Debug.Log("保存完毕:" + path);

      
        //if (PhotoWallInterface.Instance != null)
        //PhotoWallInterface.Instance.LoadByIO(path);//IO方式加载图片


        if (Finish != null)
        {
            Finish(tex, path);
        }

        //Destroy(tex);
    }

}

区域截屏方式三:

IEnumerator getScreenTexture(RectTransform rectT)
    {
        yield return new WaitForEndOfFrame();
        Texture2D screenShot = new Texture2D((int)rectT.rect.width, (int)rectT.rect.height, TextureFormat.RGB24, true);
        float x = rectT.localPosition.x + (Screen.width - rectT.rect.width) / 2;
        float y = rectT.localPosition.y + (Screen.height - rectT.rect.height) / 2;
        Rect position = new Rect(x, y, rectT.rect.width, rectT.rect.height);
        screenShot.ReadPixels(position, 0, 0, true);//按照设定区域读取像素;注意是以左下角为原点读取
        screenShot.Apply();

        string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        string filePath = "";
        filePath = Application.persistentDataPath + "/HeadFold";
        string scrPathName = filePath + "/" + fileName;
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        //二进制转换
        byte[] byt = screenShot.EncodeToPNG();
        File.WriteAllBytes(scrPathName, byt);
        System.Diagnostics.Process.Start(scrPathName);
    }

截屏方式四:

读取RenderTexture 纹理


public void OnUserSave()
{
    var prePath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/"));
    string path = prePath + string.Format("/SaveFX/EFX{0}.png",index);
    Save(path, CreateFrom(target));
    index++;
}
 
public void Save(string path, Texture2D texture2D)
{
    Debug.Log("Save Path:" + path);
    var bytes = texture2D.EncodeToPNG();
    //var bytes = texture2D.EncodeToJPG();
    System.IO.File.WriteAllBytes(path, bytes);
}

public Texture2D CreateFrom(RenderTexture renderTexture)
{
    Texture2D texture2D = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
    var previous = RenderTexture.active;
    RenderTexture.active = renderTexture;
 
    texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
 
    RenderTexture.active = previous;
 
    texture2D.Apply();
 
    return texture2D;
}

备注:

保存图片

	byte[] bytes = tex.EncodeToPNG();
  	string texName = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".png";
    File.WriteAllBytes(Application.streamingAssetsPath + "/HBTexture/" + texName + ".png", bytes);
posted @ 2022-06-22 18:05  哒哒哒~~~  阅读(576)  评论(0编辑  收藏  举报