unity ios 截屏

作者: su9257_海澜 | 来源:发表于2017-11-01 10:33 被阅读93次

最近项目需要ios响应的截屏功能,参考网上一些资料,code如下

需要注意的是:IOS的XCODE打包要选择打开相册权限,否则截图会闪退!!!

点击加号添加响应权限的字符串,权限字符串列表如下:

  • NSContactsUsageDescription -> 通讯录
  • NSMicrophoneUsageDescription -> 麦克风
  • NSPhotoLibraryUsageDescription -> 相册
  • NSLocationAlwaysUsageDescription -> 地理位置
  • NSLocationWhenInUseUsageDescription -> 地理位置
  • 使用相机NSCameraUsageDescription

对应截屏需要的 .m 文件下载

.m对应Code(首先把传入的文件转换成NSString,然后转换成UIImage保存到相册中)

int saveToGallery(const char *path)
{
    NSString *imagePath = [NSString stringWithUTF8String:path];
    
    NSLog(@"###### This is the file path being passed: %@", imagePath);
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:imagePath])
    {
        NSLog(@"###### Early exit - file doesn't exist");
        return 0;
    }
    
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    if(image)
    {
        NSLog(@"###### Trying to write image");
        UIImageWriteToSavedPhotosAlbum( image, nil, NULL, NULL );
        return 1;
    }
    
    return 0;
}

Unity响应的Code

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;

public class PluginsForIOS : MonoBehaviour
{

    public const string Name = "PluginsForIOS";
    static PluginsForIOS() { }
    protected PluginsForIOS() { }
    protected static volatile PluginsForIOS instance = null;
    protected readonly object syncRoot = new object();
    protected static readonly object staticSyncRoot = new object();

    public static PluginsForIOS Instance
    {
        get
        {
            if (instance == null)
            {
                lock (staticSyncRoot)
                {
                    if (instance == null)
                    {
                        GameObject PluginsForIOSObj = new GameObject(Name);
                        instance = PluginsForIOSObj.AddComponent<PluginsForIOS>();
                    }
                }
            }
            return instance;
        }
    }

    #region ScreenShot

    public string Prefix = "MyScreenshot";
    public string AlbumName = "MyApp";

    private bool IsWriting = false;

    [DllImport("__Internal")]
    private static extern int saveToGallery(string path);

    #endregion
    private void Awake()
    {
        instance = this;
    }
    private void Start()
    {
        AlbumName = Application.persistentDataPath + "/" + AlbumName;

        if (!Directory.Exists(AlbumName))
        {
            Directory.CreateDirectory(AlbumName);
        }
    }

    #region ScreenShot
    public static void BeginScreenShot()
    {
        if (!Instance.IsWriting)
        {
            Instance.StartCoroutine(Instance.ScreenShot());
        }
    }

    IEnumerator ScreenShot()
    {
        IsWriting = true;

        int photoSaved = 0;
        string date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff").Replace(":", "-");
        string screenshotFilename = Prefix + "_" + date + ".png";
        if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            string iosPath = Application.persistentDataPath + "/" + screenshotFilename;
            //初始化
            Texture2D photo = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
            yield return new WaitForEndOfFrame();
            //读取像素并应用
            photo.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
            photo.Apply();
            //转换对应的byte数组
            byte[] data = photo.EncodeToPNG();
            DestroyImmediate(photo);
            photo = null;

            // System.IO.File.WriteAllBytes(iosPath, data);//和下面的是两种序列化方式,而下面用的可以避免屏幕卡顿
            FileStream file = File.Open(iosPath, FileMode.Create);
            file.BeginWrite(data, 0, data.Length, new AsyncCallback(endWriter), file);

            while (photoSaved == 0)
            {
                photoSaved = saveToGallery(iosPath);
                Debug.Log("等待IOS反馈");
                yield return new WaitForSeconds(.5f);
            }

            UnityEngine.iOS.Device.SetNoBackupFlag(iosPath);//在这些文件上设置“ 无备份”标志,以防止它们备份到iCloud。
        }
        else
        {
            Debug.Log("此设备不支持截屏");
        }
        yield return null;
    }

    public void endWriter(IAsyncResult end)
    {
        using (FileStream file = (FileStream)end.AsyncState)
        {
            file.EndWrite(end);
            Debug.Log("异步完成");
            IsWriting = false;
        }
    }

    #endregion
}

相关文章

  • Unity功能记录(一) ------ 截图/录屏保存到相册(A

    截屏和录屏unity端代码都已经分享过 :Unity功能记录(十七) ------ 截屏功能Unity插件(二) ...

  • unity ios 截屏

    最近项目需要ios响应的截屏功能,参考网上一些资料,code如下 需要注意的是:IOS的XCODE打包要选择打开相...

  • Unity踩坑日志:关于unity与iOS交互的坑

    在原生中调用unity导出的iOS工程 1.一个需求是进行截屏,同时隐藏UI,截屏之后显示UI,并显示“已保存至系...

  • flutter:截屏

    1.flutter-截屏组件 2.flutter-截屏插件 3.flutter-iOS原生截屏 iOS代码 4.获...

  • (最新)iOS截屏

    ios webview 截屏:ios截屏 前言:介绍一下截屏有很多种做法1:截当前屏幕内容2:截整个视图的所有内容...

  • ios截屏

    ios截屏

  • Unity截屏

    屏幕截图时需要在协程中执行,且必须有yield return new WaitForEndOfFrame();,否...

  • Unity编辑器录屏神器:Unity Recorder

    摘要:汇报工作进展时你还在使用截屏或者录屏软件?来试试Unity Recorder插件,一站解决截屏、录屏、全景图...

  • iOS 应用内截屏分享

    需求:捕获用户截屏操作,并建议用户截屏后的操作。虽然iOS11 有系统的截屏,但 APP 内截屏可便捷操作。 封装...

  • iOS 截屏&长截屏

    截屏在 iOS 开发中经常用到,本篇文章讲的是监听用户截屏操作,并且获取截屏图片,如果当前是UIScrollVie...

网友评论

    本文标题:unity ios 截屏

    本文链接:https://www.haomeiwen.com/subject/fqjwpxtx.html