首页 > 其他分享 >unity 利用相机截图,可以截取UI,保存png格式,可用于签名抠图

unity 利用相机截图,可以截取UI,保存png格式,可用于签名抠图

时间:2023-01-11 13:34:11浏览次数:45  
标签:rt RenderTexture screenShot unity camera UI rect new png

 public Camera cam;
    void Start()
    {
        StartCoroutine(CaptureAlphaCamera(cam,new Rect(0,0,1920,1080)));
    }

    #region 截取透明图
    /// <summary>
    /// 3.对相机截图。 
    /// </summary>
    IEnumerator CaptureAlphaCamera(Camera camera,Rect rect) {
        yield return new WaitForEndOfFrame();

        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)Screen.width,(int)Screen.height,0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();

        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width,(int)rect.height,TextureFormat.ARGB32,false);
        screenShot.ReadPixels(rect,0,0);
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);

        // 最后将这些纹理数据,成一个png图片文件
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename,bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}",filename));

        //及时垃圾清理
        System.GC.Collect();
        //return screenShot;
    }

 

 

 

 

 

 

标签:rt,RenderTexture,screenShot,unity,camera,UI,rect,new,png
From: https://www.cnblogs.com/zqiang0803/p/17043442.html

相关文章