wxr
2020-03-05 0bdc0a135dbe31761b53f432ed34f347f0a4e36b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using System;
using AVFoundation;
using CoreGraphics;
using Foundation;
using UIKit;
 
namespace Shared
{
    /// <summary>
    /// 拍照或者选择图片
    /// </summary>
    public static class Camera
    {
        static readonly UIImagePickerController _picker;
        static bool IsZoom;
 
        /// <summary>
        /// 拍照或者读取图片完成时调用的动作,string==null表示用户取消了拍照或者取消选择图片,string!=null,表示图片的路径
        /// </summary>
        static Action<string> _callback;
 
        static Camera()
        {
            _picker = new UIImagePickerController();
            _picker.Delegate = new MyCameraDelegate();
        }
 
        static string _fileName;
 
        /// <summary>
        /// Camera delegate.
        /// </summary>
        class MyCameraDelegate : UIImagePickerControllerDelegate
        {
            //16*9
            public override void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info)
            {
                picker.DismissModalViewController(true);
 
                var tempPhoto = info.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
 
                tempPhoto = rotateImage(tempPhoto);
                var width = tempPhoto.CGImage.Width;
                var height = tempPhoto.CGImage.Height;
                //System.Console.WriteLine("原宽度=" + width + "高度=" + height);
 
                nfloat noScale = width / height;
                nfloat scale = 16.0f / 9.0f;
                if (!IsZoom)
                {
                    scale = noScale;
                }
                nfloat x = 0, y = 0, w = width, h = height;
                if (scale < noScale)
                {
                    w = height * scale;
                    x = (width - w) / 2;
                }
                else
                {
                    h = width / scale;
                    y = (height - h) / 2;
                }
 
 
 
                var imageRef = tempPhoto.CGImage.WithImageInRect(new CGRect(x, y, w, h));
                UIImage newImage = UIImage.FromImage(imageRef);
 
 
                // 关闭上下文
                //System.Console.WriteLine("改变后的宽度=" + newImage.Size.Width + "高度=" + newImage.Size.Height);
                string tempFilePath = System.IO.Path.Combine(Application.RootPath, _fileName);
                NSError err = null;
                float f = 0.1f;
                NSData nsData = newImage.AsJPEG(f);
                while (f < 1.0f)
                {
                    if (200 * 1024 < nsData.Length)
                    {
                        break;
                    }
                    f += 0.1f;
                    nsData = newImage.AsJPEG(f);
                }
                if (nsData.Save(tempFilePath, false, out err))
                {
                    //保存成功
                }
                else
                {
                    Console.WriteLine("保存图片失");
                }
                newImage.Dispose();
                _callback?.Invoke(tempFilePath);
                _callback = null;
            }
 
            public override void Canceled(UIImagePickerController picker)
            {
                picker.DismissModalViewController(true);
                _callback?.Invoke(null);
                _callback = null;
            }
 
            UIImage rotateImage(UIImage aImage)
            {
                var imgRef = aImage.CGImage;
                var width = imgRef.Width;
                var height = imgRef.Height;
                CGAffineTransform transform = CGAffineTransform.MakeIdentity();
                CGRect bounds = new CGRect(0, 0, width, height);
                nfloat scaleRatio = 1;
                nfloat boundHeight;
                UIImageOrientation orient = aImage.Orientation;
                nfloat M_PI = 3.14159265358979323846f;
 
                switch (orient)
                {
                    case UIImageOrientation.Up: //EXIF = 1
                        transform = CGAffineTransform.MakeIdentity();
                        break;
                    case UIImageOrientation.UpMirrored: //EXIF = 2
                        transform = CGAffineTransform.MakeTranslation(width, 0.0f);
                        transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f);
                        break;
                    case UIImageOrientation.Down: //EXIF = 3
                        transform = CGAffineTransform.MakeTranslation(width, height);
                        transform = CGAffineTransform.Rotate(transform, M_PI);
                        break;
                    case UIImageOrientation.DownMirrored: //EXIF = 4
                        transform = CGAffineTransform.MakeTranslation(0.0f, height);
                        transform = CGAffineTransform.Scale(transform, 1.0f, -1.0f);
                        break;
                    case UIImageOrientation.LeftMirrored: //EXIF = 5
                        boundHeight = bounds.Height;
                        bounds.Height = bounds.Size.Width;
                        bounds.Width = boundHeight;
                        transform = CGAffineTransform.MakeTranslation(height, width);
                        transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f);
                        transform = CGAffineTransform.Rotate(transform, 3.0f * M_PI / 2.0f);
                        break;
                    case UIImageOrientation.Left: //EXIF = 6
                        boundHeight = bounds.Height;
                        bounds.Height = bounds.Width;
                        bounds.Width = boundHeight;
                        transform = CGAffineTransform.MakeTranslation(0.0f, width);
                        transform = CGAffineTransform.Rotate(transform, 3.0f * M_PI / 2.0f);
                        break;
                    case UIImageOrientation.RightMirrored: //EXIF = 7
                        boundHeight = bounds.Height;
                        bounds.Height = bounds.Width;
                        bounds.Width = boundHeight;
                        transform = CGAffineTransform.MakeScale(-1.0f, 1.0f);
                        transform = CGAffineTransform.Rotate(transform, M_PI / 2.0f);
                        break;
                    case UIImageOrientation.Right: //EXIF = 8
                        boundHeight = bounds.Height;
                        bounds.Height = bounds.Width;
                        bounds.Width = boundHeight;
                        transform = CGAffineTransform.MakeTranslation(height, 0.0f);
                        transform = CGAffineTransform.Rotate(transform, M_PI / 2.0f);
                        break;
                        //default:
                        // [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
                }
 
                UIGraphics.BeginImageContext(bounds.Size);
                var context = UIGraphics.GetCurrentContext();
                if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left)
                {
                    context.ScaleCTM(-scaleRatio, scaleRatio);
                    context.TranslateCTM(-height, 0);
                }
                else
                {
                    context.ScaleCTM(scaleRatio, -scaleRatio);
                    context.TranslateCTM(0, -height);
                }
 
                context.ConcatCTM(transform);
                UIGraphics.GetCurrentContext().DrawImage(new CGRect(0, 0, width, height), imgRef);
                UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext();
                imgRef.Dispose();
                UIGraphics.EndImageContext();
                return imageCopy;
            }
        }
 
        /// <summary>
        /// 拍照
        /// </summary>
        /// <param name="callback">回调函数</param>
        /// <param name="fileName">文件名</param>
        public static void TakePicture(Action<string> callback, string fileName, bool isZoom = true)
        {
            _fileName = fileName;
            _callback = callback;
            _picker.SourceType = UIImagePickerControllerSourceType.Camera;
            IsZoom = isZoom;
            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                if (!UIImagePickerController.IsCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front))
                {
                    return;
                }
                _picker.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve;
                currentVC.PresentModalViewController(_picker, true);
            }
            else
            {
                currentVC.PresentModalViewController(_picker, true);
            }
        }
 
        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="callback">回调函数</param>
        /// <param name="fileName">文件名</param>
        public static void SelectPicture(Action<string> callback, string fileName, bool isZoom = true)
        {
            _fileName = fileName;
            _callback = callback;
            _picker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            IsZoom = isZoom;
            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                NSOperationQueue.MainQueue.AddOperation(() =>
                {
                    _picker.ModalTransitionStyle = UIModalTransitionStyle.CoverVertical;
                    var popover = new UIPopoverController(_picker) { PopoverContentSize = Application.RootFrameLayout.Frame.Size };
                    popover.PresentFromRect(new CGRect(95, 235, 300, 300), Application.RootFrameLayout, UIPopoverArrowDirection.Down | UIPopoverArrowDirection.Left, true);
                });
            }
            else
            {
                currentVC.PresentModalViewController(_picker, true);
            }
        }
 
        //获取当前屏幕显示的viewcontroller
        static UIViewController currentVC
        {
            get
            {
                var rootViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                var currentVC = getCurrentVCFrom(rootViewController);
                return currentVC;
            }
        }
 
        static UIViewController getCurrentVCFrom(UIViewController rootVC)
        {
            UIViewController currentVC;
            if (rootVC.PresentedViewController != null)
            {
                // 视图是被presented出来的
                rootVC = rootVC.PresentedViewController;
            }
            if (rootVC.GetType() == typeof(UITabBarController))
            {
                // 根视图为UITabBarController
                currentVC = getCurrentVCFrom((rootVC as UITabBarController).SelectedViewController);
            }
            else if (rootVC.GetType() == typeof(UINavigationController))
            {
                // 根视图为UINavigationController
                currentVC = getCurrentVCFrom((rootVC as UINavigationController).VisibleViewController);
            }
            else
            {
                // 根视图为非导航类
                currentVC = rootVC;
            }
            return currentVC;
        }
    }
}