unity3d 截图方法 ios和android均适用

  public static void SaveScreenshot(string fileName, string albumName = "MyScreenshots", string fileType = "jpg", Rect screenArea = default(Rect))
    {

        if (screenArea == default(Rect))
            screenArea = new Rect(0, 0, Screen.width, Screen.height);
        // screenArea = new Rect(Screen.width * 0.04f, Screen.height * 0.18f, Screen.width, Screen.height); //从某个点位置开始截图
        Instance.StartCoroutine(Instance.GrabScreenshot(fileName, albumName, fileType, screenArea));
    }

    IEnumerator GrabScreenshot(string fileName, string albumName, string fileType, Rect screenArea)
    {
        yield return new WaitForEndOfFrame();

        Texture2D texture = new Texture2D((int)screenArea.width, (int)screenArea.height, TextureFormat.RGB24, false);
        //Texture2D texture = new Texture2D((int)(0.92 * Screen.width), (int)(0.43 * Screen.height), TextureFormat.RGB24, false);//截图的大小


        texture.ReadPixels(screenArea, 0, 0);
        texture.Apply();
        byte[] bytes;
        string fileExt;

        if (fileType == "png")
        {
            bytes = texture.EncodeToPNG();
            fileExt = ".png";
        }
        else
        {
            bytes = texture.EncodeToJPG();
            fileExt = ".jpg";
        }

        string date = System.DateTime.Now.ToString("hh-mm-ss_dd-MM-yy");
        string screenshotFilename = fileName + "_" + date + fileExt;
        string path = Application.persistentDataPath + "/" + screenshotFilename;

        System.IO.File.WriteAllBytes(path, bytes);

}
注:  如果是在IOS打包的话 请在Xcode 打包时找到info.plis 文件  右键 Open as=> information property list  中添加  Privacy- Photo 字段开头的两个字段   避免截图时卡死或闪退

猜你喜欢

转载自blog.csdn.net/weixin_41573444/article/details/82184866