unity ios 截屏

  1. 云栖社区>
  2. 博客>
  3. 正文

unity ios 截屏

su9257_海澜 2017-11-01 10:33:00 浏览382
展开阅读全文

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

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

img_663b8c980e141f03e3eb914f3a263cfe.png

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

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

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

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

img_9a23b2c25d1e822962a8f51ad3bc08eb.png
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
}

网友评论

登录后评论
0/500
评论
su9257_海澜
+ 关注