Unity iOS截圖並儲存到手機相簿總結
阿新 • • 發佈:2018-12-14
unity截圖方法
using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.UI; public class Screenshots : MonoBehaviour { [DllImport("__Internal")] private static extern void _SavePhoto(string readAddr); public RawImage rimg; WebCamTexture wbct; string path_save; string path_read; void Start() { wbct = new WebCamTexture(); for (int i = 0; i < WebCamTexture.devices.Length; i++) { if (!WebCamTexture.devices[i].isFrontFacing) { wbct.deviceName = WebCamTexture.devices[i].name; break; } } rimg.gameObject.SetActive(false); } public void startScreenshots() { rimg.gameObject.SetActive(true); rimg.texture = wbct; wbct.Play(); } public void Screenshoting() { wbct.Pause(); System.DateTime now = System.DateTime.Now; string filename = string.Format("image{0}{1}{2}{3}{4}.png", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); path_save = filename; path_read = Application.persistentDataPath + "/" + path_save; ScreenCapture.CaptureScreenshot(path_save); _SavePhoto(path_read); } }
在xcode中新建檔案
選擇標頭檔案Header File,命名為PhotoManager,新增程式碼如下:
#import <Foundation/Foundation.h>
@interface PhotoManager : NSObject
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
contextInfo: ( void *) contextInfo;
@end
再新建檔案,選擇執行檔案Objective-C File
#import "PhotoManager.h" @implementation PhotoManager - ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error contextInfo: ( void *) contextInfo { NSLog(@"儲存結束"); if (error != nil) { NSLog(@"有錯誤"); } } void _SavePhoto(char *readAddr) { NSString *strReadAddr = [NSString stringWithUTF8String:readAddr]; UIImage *img = [UIImage imageWithContentsOfFile:strReadAddr]; NSLog([NSString stringWithFormat:@"w:%f, h:%f", img.size.width, img.size.height]); PhotoManager *instance = [PhotoManager alloc]; UIImageWriteToSavedPhotosAlbum(img, instance, @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil); } @end
然後在Info介面,Custom iOS Target Properties下點選 + 號新增相機許可權,如下圖所示:
選擇 Privacy-Camera Usage Description(使用相機許可權),並在後面新增提示:使用相機(可任意)。 再點選 + 號新增相簿許可權,選擇Privacy-Photo Library Additions Usage Description(相簿新增許可權),並在後面新增提示:使用相簿(可任意)。