Unity 指定区域截屏

发布时间 2023-12-14 17:03:35作者: Ww7i
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows;

/**
 *
 * Unity指定区域截图
 * Create by Camming 2020/06/13
 * 
 */
public class Screen : MonoBehaviour
{

    public Transform test;
    // Start is called before the first frame update
    void Start()
    {
        string fileName =Application.persistentDataPath+"/tfw"+"/userPic.png";
        if (!Directory.Exists(Application.persistentDataPath+"/tfw"))
        {
            Debug.LogError("Start 目录不存在 创建");
            Directory.CreateDirectory(Application.persistentDataPath+"/tfw");
        }
      
  
       IEnumerator screenCapture = CaptureByUI(test.GetComponent<RectTransform>(), fileName);
       StartCoroutine(screenCapture);
           
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    
    /// <summary>
    /// 1、获取纹理
    /// 2、计算开始坐标和长宽
    /// 3、读取像素
    /// 4、应用读取
    /// 5、将纹理转为图片byte数组
    /// 6、将图片byte数据内容写入到新创建的文件中
    /// </summary>
    /// <param name="UIRect"></param>
    /// <param name="mFileName"></param>
    /// <returns></returns>
    
    public IEnumerator CaptureByUI(RectTransform UIRect, string mFileName)
    {
        //等待帧画面渲染结束
        yield return new WaitForEndOfFrame();
 
        int width = (int)(UIRect.rect.width );
        int height = (int)(UIRect.rect.height);
 
        Texture2D screenTure = new Texture2D(width, height, TextureFormat.RGB24, false);
 
        //左下角为原点(0, 0)
        float leftBtmX = UIRect.transform.position.x + UIRect.rect.xMin ;
        float leftBtmY = UIRect.transform.position.y + UIRect.rect.yMin ;
 
        //从屏幕读取像素, leftBtmX/leftBtnY 是读取的初始位置,width、height是读取像素的宽度和高度
        screenTure.ReadPixels(new Rect(leftBtmX, leftBtmY, width, height), 0, 0);
        //执行读取操作
        screenTure.Apply();
        byte[] bytes = screenTure.EncodeToPNG();
        
        if (Directory.Exists(mFileName))
        {
            Debug.LogError("将旧的图片删除");
            Directory.Delete(mFileName);
        }
        //保存
        System.IO.File.WriteAllBytes(mFileName, bytes);
    }

}