c# - 如何统一截图,可以在IOS和Android中使用
问题描述
如何截取屏幕截图,以便我可以统一截取游戏截图,以便将其保存到 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, 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);
}
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;
}
}
}
我已经使用这种方法在 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, 0, Screen.width, Screen.height), 0, 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);
}
解决方案
推荐阅读
- c# - 在哪些情况下,异步方法将在与调用 await 之前使用的线程不同的线程中继续?
- c# - 如何获取客户端机器日期格式?
- arrays - 发送一个字符串数组并使用 parcelable kotlin 接收它
- mysql - 加入多个计数
- python - 具有重复值的数据框中的位置
- visual-studio-code - 如何使用 Visual Studio Code + VSCode remote + Chrome 调试器调试 Angular 应用程序
- java - 给定一个整数数组,如果数字序列 1、2、3 出现在数组中的某个位置,则返回 true
- database - Laravel 在查询之前更改模型表
- azure - 了解分配 Azure IP 的位置
- javascript - 如何根据数据中的变量读取数据并将标记分配给图层