unity ios 截屏

最近项目需要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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值