基于ToLua调用C#代码实现截屏功能,并保存图片到手机

5 篇文章 0 订阅

截屏原理:Camera(摄像机)是Unity中非常重要的一个组件,其中有一个属性叫做targetTexture,在设置了targetTexture后,Camera会在渲染时将其屏幕上的图像渲染到targetTexture上,预览截屏时将texture赋值给UI Texture组件即可看到截屏。当要保存截图时可以将texture转化为Png格式的图片

截屏:

public void startScreenShot(GameObject camera, GameObject uicamera, System.Action callback = null)
    {
        string times = System.DateTime.Now.Millisecond.ToString();
        filename = times + ".png";
        uicamera.GetComponent<Camera>().enabled = true;
        StartCoroutine(CaptureByCamrea(camera.GetComponent<Camera>(), uicamera.GetComponent<Camera>(), new Rect(0, 0, Screen.width, Screen.height), callback));
    }
    private IEnumerator CaptureByCamrea(Camera camera, Camera camera2, Rect rt, System.Action func = null)
    {
        yield return new WaitForEndOfFrame();
        RenderTexture render = new RenderTexture((int)rt.width, (int)rt.height, 1);
        camera.targetTexture = render;
        camera.Render();
        camera2.targetTexture = render;
        camera2.Render();
        RenderTexture.active = render;

        texture = new Texture2D((int)rt.width, (int)rt.height, TextureFormat.RGB24, false);
        texture.ReadPixels(rt, 0, 0);
        texture.Apply();

        //temptexture = texture;
        textureSize = texture.width * texture.height * 24 / 8;
        camera.targetTexture = null;
        camera2.targetTexture = null;
        RenderTexture.active = null;
        GameObject.DestroyImmediate(render); //立即删掉清除内存

        if (func != null)
        {
            func.Invoke();
        }
    }

保存图片:

/// <summary>
    /// 保存图片到相册
    /// </summary>
    public void SavePhoto()
    {
        string path = SavePhotoToLocal();
        SDKManager.GetSdkInstance().SavePhoto(path);
        System.IO.File.Delete(path);
    }

    /// <summary>
    /// 保存图片到游戏目录
    /// </summary>
    public string SavePhotoToLocal()
    {
        byte[] bytes = texture.EncodeToPNG();
        string mobilePath = Application.persistentDataPath + "/photo";
        if (!Directory.Exists(mobilePath))
        {
            Directory.CreateDirectory(mobilePath);
        }
        m_path = mobilePath + "/" + filename;
        System.IO.File.WriteAllBytes(m_path, bytes);
        // ExternalMsgHandle.externalCallHandle.SavePhoto(m_path);

        return m_path;
    }

    public void DeletePhoto()
    {
        if(!string.IsNullOrEmpty(m_path))
        {
            if(File.Exists(m_path))
                System.IO.File.Delete(m_path);
        }
    }

优秀文章参考https://www.cnblogs.com/Jimm/p/5951362.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值