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;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值