当前位置:   article > 正文

Unity功能记录(一) ------ 截图/录屏保存到相册(Android/iOS横屏竖屏都可以)

unity ios iosalbumcameracontroller saveimagetophotosalbum

截屏和录屏unity端代码都已经分享过 :
Unity功能记录(十七) ------ 截屏功能
Unity插件(二) ------ NatCorder(录屏保存到相册)

但是之前一个个的其实并没有用在项目上,可能会有点小坑,因此此次用在项目上的完整代码再次记录一下


一.截屏

Unity端代码 :
  1. void RecordFrame()
  2. {
  3. DateTime now = new DateTime();
  4. now = DateTime.Now;
  5. string filename = string.Format("image{0}{1}{2}{3}.png", now.Day, now.Hour, now.Minute, now.Second);
  6. Texture2D texture = CaptureScreen(ARControll.Instance.CaptureCamera,new Rect(0,0,Screen.width,Screen.height));
  7. string destination = "";
  8. if (Application.platform == RuntimePlatform.Android)
  9. {
  10. destination = "/mnt/sdcard/DCIM/Screenshots";
  11. if (!Directory.Exists(destination))
  12. {
  13. Directory.CreateDirectory(destination);
  14. }
  15. destination = destination + "/" + filename;
  16. Debug.Log(destination);
  17. File.WriteAllBytes(destination, texture.EncodeToPNG());
  18. // 安卓在这里需要去 调用原生的接口去 刷新一下,不然相册显示不出来
  19. using (AndroidJavaClass playerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  20. {
  21. using (AndroidJavaObject jo = playerActivity.GetStatic<AndroidJavaObject>("currentActivity"))
  22. {
  23. Debug.Log("scanFile:m_androidJavaObject ");
  24. jo.Call("scanFile", destination);
  25. }
  26. }
  27. MainControll.Instance.OpenTip(TipType.OneBtn, TipContentType.defaultTip, null, null, "拍照成功!", PanelLayer.Top);
  28. }
  29. else if (Application.platform == RuntimePlatform.IPhonePlayer)
  30. {
  31. destination = Application.persistentDataPath;
  32. if (!Directory.Exists(destination))
  33. {
  34. Directory.CreateDirectory(destination);
  35. }
  36. destination = destination + "/" + filename;
  37. File.WriteAllBytes(destination, texture.EncodeToPNG());
  38. #if UNITY_IOS
  39. IOSAlbumCamera.iosSaveImageToPhotosAlbum(destination);
  40. #endif
  41. }
  42. else
  43. {
  44. File.WriteAllBytes(Application.persistentDataPath + filename, texture.EncodeToPNG());
  45. }
  46. // cleanup
  47. Destroy(texture);
  48. }
Android刷新相册代码 :
  1. //刷新相册
  2. public void scanFile(String filePath) {
  3. //Log.i("Unity", "------------filePath"+filePath);
  4. Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
  5. scanIntent.setData(Uri.fromFile(new File(filePath)));
  6. this.sendBroadcast(scanIntent); //this是指UnityPlayerActivity
  7. }
iOS保存图片到相册代码(这里一起放了保存视频到相册的代码) :

IOSAlbumCameraController.h :

  1. #import<QuartzCore/CADisplayLink.h>
  2. @interface IOSAlbumCameraController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPopoverPresentationControllerDelegate>
  3. @end

IOSAlbumCameraController.mm :

  1. #import "IOSAlbumCameraController.h"
  2. @implementation IOSAlbumCameraController
  3. - (void)leftAction
  4. {
  5. [self interfaceOrientation:UIInterfaceOrientationPortrait];
  6. }
  7. - (void)rightAction
  8. {
  9. [self interfaceOrientation:UIInterfaceOrientationLandscapeRight];
  10. }
  11. - (void)interfaceOrientation:(UIInterfaceOrientation)orientation
  12. {
  13. if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
  14. SEL selector = NSSelectorFromString(@"setOrientation:");
  15. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
  16. [invocation setSelector:selector];
  17. [invocation setTarget:[UIDevice currentDevice]];
  18. int val = orientation;
  19. //2开始是因为0 1 两个参数已经被selector和target占用
  20. [invocation setArgument:&val atIndex:2];
  21. [invocation invoke];
  22. }
  23. }
  24. -(void)OpenCamera:(UIImagePickerControllerSourceType)type{
  25. [self interfaceOrientation:UIInterfaceOrientationPortrait];
  26. //创建UIImagePickerController实例
  27. UIImagePickerController * picker = [[UIImagePickerController alloc] init];
  28. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  29. //设置代理
  30. picker.delegate = self;
  31. //是否允许编辑 (默认为NO)
  32. picker.allowsEditing = YES;
  33. //设置照片的来源
  34. picker.sourceType = type;
  35. //展示选取照片控制器
  36. //if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary &&[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
  37. picker.modalPresentationStyle = UIModalPresentationPopover;
  38. UIPopoverPresentationController *popover = picker.popoverPresentationController;
  39. //picker.preferredContentSize = [UIScreen mainScreen].bounds.size;
  40. popover.delegate = self;
  41. popover.sourceRect = CGRectMake(0, 0, 0, 0);
  42. popover.sourceView = self.view;
  43. popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
  44. [self presentViewController:picker animated:YES completion:nil];
  45. // } else {
  46. // [self presentViewController:picker animated:YES completion:^{}];
  47. // }
  48. }
  49. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  50. [picker dismissViewControllerAnimated:YES completion:^{}];
  51. UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
  52. if (image == nil) {
  53. image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
  54. }
  55. //图片旋转
  56. if (image.imageOrientation != UIImageOrientationUp) {
  57. //图片旋转
  58. image = [self fixOrientation:image];
  59. }
  60. NSString *imagePath = [self GetSavePath:@"Temp.jpg"];
  61. [self SaveFileToDoc:image path:imagePath];
  62. }
  63. -(NSString*)GetSavePath:(NSString *)filename{
  64. NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  65. NSString *docPath = [pathArray objectAtIndex:0];
  66. return [docPath stringByAppendingPathComponent:filename];
  67. }
  68. -(void)SaveFileToDoc:(UIImage *)image path:(NSString *)path{
  69. [self interfaceOrientation:UIInterfaceOrientationLandscapeRight];
  70. UnitySendMessage("MainScriptHolder", "PicCallFunc", "Temp.jpg");
  71. NSData *data;
  72. if (UIImagePNGRepresentation(image)==nil) {
  73. data = UIImageJPEGRepresentation(image, 1);
  74. }else{
  75. data = UIImagePNGRepresentation(image);
  76. }
  77. [data writeToFile:path atomically:YES];
  78. }
  79. // 打开相册后点击“取消”的响应
  80. - (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
  81. {
  82. NSLog(@" --- imagePickerControllerDidCancel !!");
  83. [self interfaceOrientation:UIInterfaceOrientationLandscapeRight];
  84. UnitySendMessage( "MainScriptHolder", "PicCallFunc", (@"").UTF8String);
  85. [self dismissViewControllerAnimated:YES completion:nil];
  86. }
  87. #pragma mark 图片处理方法
  88. //图片旋转处理
  89. - (UIImage *)fixOrientation:(UIImage *)aImage {
  90. CGAffineTransform transform = CGAffineTransformIdentity;
  91. switch (aImage.imageOrientation) {
  92. case UIImageOrientationDown:
  93. case UIImageOrientationDownMirrored:
  94. transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
  95. transform = CGAffineTransformRotate(transform, M_PI);
  96. break;
  97. case UIImageOrientationLeft:
  98. case UIImageOrientationLeftMirrored:
  99. transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
  100. transform = CGAffineTransformRotate(transform, M_PI_2);
  101. break;
  102. case UIImageOrientationRight:
  103. case UIImageOrientationRightMirrored:
  104. transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
  105. transform = CGAffineTransformRotate(transform, -M_PI_2);
  106. break;
  107. default:
  108. break;
  109. }
  110. switch (aImage.imageOrientation) {
  111. case UIImageOrientationUpMirrored:
  112. case UIImageOrientationDownMirrored:
  113. transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
  114. transform = CGAffineTransformScale(transform, -1, 1);
  115. break;
  116. case UIImageOrientationLeftMirrored:
  117. case UIImageOrientationRightMirrored:
  118. transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
  119. transform = CGAffineTransformScale(transform, -1, 1);
  120. break;
  121. default:
  122. break;
  123. }
  124. // Now we draw the underlying CGImage into a new context, applying the transform
  125. // calculated above.
  126. CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
  127. CGImageGetBitsPerComponent(aImage.CGImage), 0,
  128. CGImageGetColorSpace(aImage.CGImage),
  129. CGImageGetBitmapInfo(aImage.CGImage));
  130. CGContextConcatCTM(ctx, transform);
  131. switch (aImage.imageOrientation) {
  132. case UIImageOrientationLeft:
  133. case UIImageOrientationLeftMirrored:
  134. case UIImageOrientationRight:
  135. case UIImageOrientationRightMirrored:
  136. // Grr...
  137. CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
  138. break;
  139. default:
  140. CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
  141. break;
  142. }
  143. // And now we just create a new UIImage from the drawing context
  144. CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
  145. UIImage *img = [UIImage imageWithCGImage:cgimg];
  146. CGContextRelease(ctx);
  147. CGImageRelease(cgimg);
  148. return img;
  149. }
  150. +(void) saveImageToPhotosAlbum:(NSString*) readAdr
  151. {
  152. NSLog(@"readAdr: ");
  153. NSLog(readAdr);
  154. UIImage* image = [UIImage imageWithContentsOfFile:readAdr];
  155. UIImageWriteToSavedPhotosAlbum(image,
  156. self,
  157. @selector(image:didFinishSavingWithError:contextInfo:),
  158. NULL);
  159. }
  160. +(void) image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
  161. {
  162. NSString* result;
  163. if(error)
  164. {
  165. result = @"图片保存到相册失败!";
  166. }
  167. else
  168. {
  169. result = @"图片保存到相册成功!";
  170. }
  171. UnitySendMessage( "MainScriptHolder", "SaveImageToPhotosAlbumCallBack", result.UTF8String);
  172. }
  173. //videoPath为视频下载到本地之后的本地路径
  174. + (void)saveVideo:(NSString *)videoPath{
  175. NSLog(@"路径:%@",videoPath);
  176. if (videoPath) {
  177. NSURL *url = [NSURL URLWithString:videoPath];
  178. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path) == NO) {
  179. NSLog(@"可以保存 ");
  180. }
  181. else
  182. { NSLog(@"不可以保存 ");
  183. }
  184. //保存相册核心代码
  185. UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, @selector(savedVedioImage:didFinishSavingWithError:contextInfo:), nil);
  186. }
  187. }
  188. //保存视频完成之后的回调
  189. + (void) savedVedioImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
  190. NSString* result;
  191. if (error) {
  192. result =@"视频保存失败";
  193. }
  194. else {
  195. result =@"保存视频成功";
  196. }
  197. UnitySendMessage( "MainScriptHolder", "SaveVedioToPhotosAlbumCallBack", result.UTF8String);
  198. }
  199. @end
  200. #if defined (__cplusplus)
  201. extern "C" {
  202. #endif
  203. // 打开相册
  204. void _iosOpenPhotoAlbums()
  205. {
  206. IOSAlbumCameraController *app = [[IOSAlbumCameraController alloc]init];
  207. UIViewController *vc = UnityGetGLViewController();
  208. [vc.view addSubview:app.view];
  209. [app OpenCamera:UIImagePickerControllerSourceTypePhotoLibrary];
  210. }
  211. void _iosSaveImageToPhotosAlbum(char* readAddr)
  212. {
  213. NSString* temp = [NSString stringWithUTF8String:readAddr];
  214. [IOSAlbumCameraController saveImageToPhotosAlbum:temp];
  215. }
  216. void _iosSaveVideoToPhotosAlbum(char* readAddr)
  217. {
  218. NSString* temp = [NSString stringWithUTF8String:readAddr];
  219. [IOSAlbumCameraController saveVideo:temp];
  220. }
  221. #if defined (__cplusplus)
  222. }
  223. #endif

unity与iOS交互代码IOSAlbumCamera.cs :

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Runtime.InteropServices;
  4. public class IOSAlbumCamera : MonoBehaviour
  5. {
  6. #if UNITY_IOS
  7. [DllImport ("__Internal")]
  8. private static extern void _iosOpenPhotoAlbums();
  9. [DllImport ("__Internal")]
  10. private static extern void _iosSaveImageToPhotosAlbum(string readAddr);
  11. [DllImport("__Internal")]
  12. private static extern void _iosSaveVideoToPhotosAlbum(string readAddr);
  13. /// <summary>
  14. /// 保存图片到相册
  15. /// </summary>
  16. /// <param name="readAddr"></param>
  17. public static void iosSaveImageToPhotosAlbum(string readAddr)
  18. {
  19. _iosSaveImageToPhotosAlbum (readAddr);
  20. }
  21. public static void iosSaveVideoToPhotosAlbum(string readAddr)
  22. {
  23. _iosSaveVideoToPhotosAlbum(readAddr);
  24. }
  25. public static void iosOpenPhotoAlbums()
  26. {
  27. _iosOpenPhotoAlbums();
  28. }
  29. #endif
  30. }

注意修改回调哦

二.录屏

unity代码请参考Unity插件(二) ------ NatCorder(录屏保存到相册)
保存到相册请参考一中iOS所有代码

17787668-4eca4da34eb71a37.png
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/728940
推荐阅读
相关标签
  

闽ICP备14008679号