它需要截图,但不会在图库中显示。屏幕截图保存到android / data / com.company.name / file.name但是我想用文件名截图直接保存到图库
到目前为止,我的代码是:
public void Capture()
{
string filename = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
Application.CaptureScreenshot(filename + ".jpg");
Debug.Log("captured screenshot");
}
寻找here(第二个)提供的答案。它完美地运作。
这是最终的代码:
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;
}
}
你只需致电:
string path = SaveImageToGallery(picture, "Test Picture", "This is a description.");
编辑:因为你似乎真的很新Unity,我建议先学习它。无论如何,这里是你如何调用上面提供的代码:
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);
}
只需将这两种方法添加到您的代码中,然后从另一个脚本,Unity按钮或其他任何内容调用CaptureScreenshot()
......
希望这可以帮助,