如何拍摄屏幕快照,以便可以统一拍摄游戏内屏幕快照,以便将其保存到IOS和Android中的图库中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TakeScreenshot : MonoBehaviour {
[SerializeField]
GameObject blink;
public Text text;
public Transform canvas;
protected const string MEDIA_STORE_IMAGE_MEDIA = "android.provider.MediaStore$Images$Media";
protected static AndroidJavaObject m_activity;
public void TakeAShot()
{
StartCoroutine(CaptureIt(Screen.width,Screen.height));
}
IEnumerator CaptureIt(int width,int height)
{
yield return new WaitForEndOfFrame();
Texture2D tex = new Texture2D(width,height);
tex.ReadPixels(new Rect(0,width,height),0);
tex.Apply();
yield return tex;
string path = SaveImageToGallery(tex,"Name","Description");
Debug.Log("Picture has been saved at:\n" + path);
}
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,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;
}
}
}
我已经使用此方法在Android画廊中拍摄并保存了屏幕截图,但是无法在iOS中将其保存。有人可以帮我吗?
我尝试使用建议的修改,但还是没有运气。现在我的代码看起来像这样。
public void TakeAShot()
{
StartCoroutine(TakeScreenshotAndSave());
}
private IEnumerator TakeScreenshotAndSave()
{
yield return new WaitForEndOfFrame();
Texture2D ss = new Texture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
ss.ReadPixels(new Rect(0,Screen.width,Screen.height),0);
ss.Apply();
// Save the screenshot to Gallery/Photos
Debug.Log("Permission result: " + NativeGallery.SaveImageToGallery(ss,"GalleryTest","Image.png"));
// To avoid memory leaks
Destroy(ss);
}