实际上,我正在尝试截取屏幕截图并将其保存到 Android 图库中,为此我使用了一个开源库“Unity Native Gallery”,我的代码如下:
NativeGallery.Permission permission = NativeGallery.CheckPermission();
if (permission == NativeGallery.Permission.Granted) {
Debug.Log("May proceed");
}
else {
Debug.Log("Not allowed");
}
// Output ==> "May Proceed"
Debug.Log("Path is "+NativeGallery.GetSavePath("GalleryTest","My_img_{0}.png"));
//Output ==> /storage/emulated/0/DCIM/GalleryTest/My_img_1.png
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();
Debug.Log("Secondlast");
permission = NativeGallery.SaveImageToGallery( ss, "GalleryTest", "My_img_{0}.png" ) ;
Debug.Log("Done screenshot");
但我的它从不保存屏幕截图,当我看到控制台时,我得到了 2 个重要的日志
1.我的调试日志“SecondLast”打印在控制台上但不是最后一个“完成截图”
2.出现异常打印“UnauthorizedAccessException:访问路径“/storage/emulated/0/DCIM/GalleryTest/My_img_1.png”被拒绝。”
要点:- 我已经在统一播放器设置中设置了对外部 (SDCard) 的写入权限。 (实际上我尝试使用“内部”和“外部”两种设置)
最佳答案
我看了他们的repo,用你提供的源代码,不管你有没有权限,你似乎都在试图截屏并保存它。这可能是您的问题:
NativeGallery.Permission permission = NativeGallery.CheckPermission();
if (permission == NativeGallery.Permission.Granted)
{
Debug.Log("May proceed");
}
else
{
Debug.Log("Not allowed");
// You do not break out of the function here so it will attempt to save anyways
}
你应该看起来像这样:
NativeGallery.Permission permission = NativeGallery.CheckPermission();
if (permission == NativeGallery.Permission.ShouldAsk)
{
permission = NativeGallery.RequestPermission();
Debug.Log("Asking");
}
// If we weren't denied but told to ask, this will handle the case if the user denied it.
// otherwise if it was denied then we return and do not attempt to save the screenshot
if (permission == NativeGallery.Permission.Denied)
{
Debug.Log("Not allowed");
return;
}
Debug.Log("Path is "+NativeGallery.GetSavePath("GalleryTest","My_img_{0}.png"));
//Output ==> /storage/emulated/0/DCIM/GalleryTest/My_img_1.png
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();
Debug.Log("Secondlast");
permission = NativeGallery.SaveImageToGallery( ss, "GalleryTest", "My_img_{0}.png" ) ;
Debug.Log("Done screenshot");
关于C# 统一脚本使用库 UnityNativeGallery 在 android 库中获取和保存屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875097/