Unity截图

什么都不说了,直接上代码。

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

public class CutImage : MonoBehaviour 
{
    public Vector2 startPos;     //鼠标开始位置
    public Vector2 endPos;   //鼠标结束位置
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            startPos = Input.mousePosition;
        }
        if(Input.GetMouseButtonUp(0))
        {
            endPos = Input.mousePosition;
            StartCoroutine(CreateImage());   //当鼠标按键抬起,开始截图
        }

    }

    IEnumerator CreateImage()
    {
        int width = (int)(endPos.x - startPos.x);      //图片宽
        int height = (int)(startPos.y - endPos.y);     //图片高
        Texture2D image = new Texture2D(width, height,TextureFormat.ARGB32, true);   //创建一个纹理
        Rect rect = new Rect(startPos.x, Screen.height - (Screen.height - endPos.y), width, height);      //在屏幕上截取一个矩形
        yield return new WaitForEndOfFrame();    //等待帧结束

        image.ReadPixels(rect,0, 0,  true);   //在屏幕的规定区域内读取像素
        image.Apply();       //转化成图片
        yield return image;

        byte[] bs = image.EncodeToPNG();      //把图片转化成二进制
        File.WriteAllBytes(Application.dataPath + "/Image.png", bs);     //把图片街道本地
        yield return null;
    }

}
原文地址:https://www.cnblogs.com/ZhiXing-Blogs/p/5578765.html