保存图片到相册中,让系统扫描新加的图片
public IEnumerator CaptureScreenShow()
{
    yield return new WaitForEndOfFrame();
    string fileName = DateTime.Now.Ticks.ToString();
    string tagerFolder = DateTime.Now.ToString("yyyy-MM-dd");
        

    Texture2D t = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
    t.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
    t.Apply();

    byte[] byt = t.EncodeToPNG();
    string SaveImagePath = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android")) + "/Pictures/Screenshots";
    string pathName = Path.Combine( SaveImagePath , tagerFolder );
    if (!Directory.Exists(pathName))
    {
        Directory.CreateDirectory(pathName);
    }
    string path = pathName + "/" + fileName + ".png";
    File.WriteAllBytes(path, byt);

    yield return null;

    //判断是否截图成功
    if (File.Exists(path))
    {
#if UNITY_ANDROID //刷新相册
        ScanFile(new string[] { pathName });
#endif

    }
    else {
        GlobalHallUIMgr.Instance.ShowSystemTipsUI(StringTable.GetString("givescore_cap_pic_err"), 1f, false);
    }
}

void ScanFile(string[] path)
{
    using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
    {
        AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
        using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
        {
            Conn.CallStatic("scanFile", playerActivity, path, null, null);
        }
    }
}


截图成功后,如果只是保存到了某个目录上,手机是不会马上立刻的发现那张图片的,比如说,你要微信发送某张图片,如果手机都不知道有那张图片,自然就发送不到了,只能去指定目录分享了。

所以截图成功保存后,调用一下Android扫描文件API。


首页 我的博客
粤ICP备17103704号