Captura de tela Unity Texture2D

	/// <summary>
    /// 截图
    /// </summary>
    /// <param name="filePath">ref  图片保存地址</param>
    /// <param name="isAutoDestroy">true -> 销毁;false -> 不销毁</param>
    /// <param name="isFull">true -> 全屏;false -> 部分区域</param>
    /// <param name="target">中心锚点</param>
    /// <returns></returns>
    public static Texture2D ScreenShot(ref string filePath, bool isAutoDestroy = false, bool isAutoSave = true, bool isFull = true, RectTransform target = null)
    {
    
    
        Canvas canvas = null;  //获取一下画布

        Texture2D m_screenTure;
        byte[] bytes;
        if (isFull)
        {
    
    
            m_screenTure = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
            m_screenTure.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        }
        else
        {
    
    
            Vector2 screenVec = RectTransformUtility.WorldToScreenPoint(Camera.main,target.transform.position);
            float widthSize = target.rect.size.x / canvas.GetComponent<RectTransform>().rect.size.x * Screen.width;
            float heighSize = target.rect.size.y / canvas.GetComponent<RectTransform>().rect.size.y * Screen.height;

            m_screenTure = new Texture2D((int)widthSize, (int)heighSize, TextureFormat.RGB24, false);
            m_screenTure.ReadPixels(new Rect(screenVec.x - widthSize / 2, screenVec.y - heighSize / 2, (int)widthSize, (int)heighSize), 0, 0);
        }

        //执行读取操作 
        m_screenTure.Apply();

        if (isAutoSave)
        {
    
    
            bytes = m_screenTure.EncodeToPNG();

            filePath = string.Concat("MyFilePath", ".png");

            FileOperation.SaveFileByBytes(filePath, bytes, true, true);

            Array.Clear(bytes, 0, bytes.Length);
        }


        if (isAutoDestroy)
        {
    
    
            GameObject.Destroy(m_screenTure);
        }

        return m_screenTure;
    }

Acho que você gosta

Origin blog.csdn.net/weixin_47819574/article/details/129438363
Recomendado
Clasificación