是否有可能在Android中捕获屏幕截图并将其保存到具有统一

时间:2017-06-28 15:17:16

标签: java c# unity3d plugins

我有Unity的免费版本,我可以捕获屏幕截图并在内部存储中保存自定义路径,以便在库中显示吗?

可以使用托管插件来实现统一吗?

到目前为止,我尝试了各种插件,但没有一个适用于我。

protected const string MEDIA_STORE_IMAGE_MEDIA = "android.provider.MediaStore$Images$Media";
protected static AndroidJavaObject m_Activity;

protected static string SaveImageToGallery(Texture2D a_Texture, string a_Title, string a_Description)
{
    using (AndroidJavaClass mediaClass = new AndroidJavaClass(MEDIA_STORE_IMAGE_MEDIA))
    {
        using (AndroidJavaObject contentResolver = Activity.Call<AndroidJavaObject>("getContentResolver"))
        {
            AndroidJavaObject image = Texture2DToAndroidBitmap(a_Texture);
            return mediaClass.CallStatic<string>("insertImage", contentResolver, image, a_Title, a_Description);
        }
    }
}

protected static AndroidJavaObject Texture2DToAndroidBitmap(Texture2D a_Texture)
{
    byte[] encodedTexture = a_Texture.EncodeToPNG();
    using (AndroidJavaClass bitmapFactory = new AndroidJavaClass("android.graphics.BitmapFactory"))
    {
        return bitmapFactory.CallStatic<AndroidJavaObject>("decodeByteArray", encodedTexture, 0, encodedTexture.Length);
    }
}

protected static AndroidJavaObject Activity
{
    get
    {
        if (m_Activity == null)
        {
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            m_Activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        }
        return m_Activity;
    }
}




public void CaptureScreenshot()
{
    StartCoroutine(CaptureScreenshotCoroutine(Screen.width, Screen.height));
}

private IEnumerator CaptureScreenshotCoroutine(int width, int height)
{
    yield return new WaitForEndOfFrame();
    Texture2D tex = new Texture2D(width, height);
    tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
    tex.Apply();

    yield return tex;
    string path = SaveImageToGallery(tex, "Name", "Description");
    Debug.Log("Picture has been saved at:\n" + path);
}

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

string ImagePath = "file:///storage/emulated/0/<FileSystemRoot>/";
Texture2D texCopy = new Texture2D(tex.width, tex.height, tex.format, tex.mipmapCount > 1);
File.WriteAllBytes(ImagePath, tex.GetRawTextureData());

查看this answer