-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCameraViewController.m
285 lines (197 loc) · 11.7 KB
/
CameraViewController.m
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
280
281
282
283
284
285
//
// CameraViewController.m
// Blocstagram_V3
//
// Created by Diego Aguirre on 6/17/15.
// Copyright (c) 2015 Diego Aguirre. All rights reserved.
//
#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "CameraToolBar.h"
#import "UIImage+ImageUtilities.h"
#import "CropBox.h"
#import "ImageLibraryViewController.h"
@interface CameraViewController () <CameraToolBarDelegate, ImageLibraryViewControllerDelegate>
@property (nonatomic, strong) UIView *imagePreview;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput;
@property (nonatomic, strong) CropBox *cropBox;
@property (nonatomic, strong) UIToolbar *topView;
@property (nonatomic, strong) UIToolbar *bottomView;
@property (nonatomic, strong) CameraToolBar *cameraToolbar;
@end
@implementation CameraViewController
#pragma mark - Build View Hierarchy
-(void)viewDidLoad{
[super viewDidLoad];
[self createViews];
[self addViewsToViewHierarchy];
[self setupImageCapture];
[self createCancelButton];
}
- (void) createCancelButton {
UIImage *cancelImage = [UIImage imageNamed:@"x"];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithImage:cancelImage style:UIBarButtonItemStyleDone target:self action:@selector(cancelPressed:)];
self.navigationItem.leftBarButtonItem = cancelButton;
}
- (void) setupImageCapture {
// #1
self.session = [[AVCaptureSession alloc] init];
self.session.sessionPreset = AVCaptureSessionPresetHigh;
// #2
self.captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.captureVideoPreviewLayer.masksToBounds = YES;
[self.imagePreview.layer addSublayer:self.captureVideoPreviewLayer];
// #3
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
// #4
if (granted) {
// #5
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// #6
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:error.localizedDescription message:error.localizedRecoverySuggestion preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK button") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self.delegate cameraViewController:self didCompleteWithImage:nil];
}]];
[self presentViewController:alertVC animated:YES completion:nil];
} else {
// #7
[self.session addInput:input];
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
self.stillImageOutput.outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG};
[self.session addOutput:self.stillImageOutput];
[self.session startRunning];
}
} else {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Camera Permission Denied", @"camera permission denied title")
message:NSLocalizedString(@"This app doesn't have permission to use the camera; please update your privacy settings.", @"camera permission denied recovery suggestion")
preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK button") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self.delegate cameraViewController:self didCompleteWithImage:nil];
}]];
[self presentViewController:alertVC animated:YES completion:nil];
}
});
}];
}
- (void)addViewsToViewHierarchy{
NSMutableArray *views = [@[self.imagePreview,self.cropBox,self.topView, self.bottomView]mutableCopy];
[views addObject:self.cameraToolbar];
for (UIView *view in views){
[self.view addSubview:view];
}
}
- (void)createViews{
self.imagePreview = [UIView new];
self.topView = [UIToolbar new];
self.bottomView = [UIToolbar new];
self.cropBox = [CropBox new];
self.cameraToolbar = [[CameraToolBar alloc] initWithImageNames:@[@"rotate",@"road"]];
self.cameraToolbar.delegate = self;
UIColor *whiteBG = [UIColor colorWithWhite:1.0 alpha:.15];
self.topView.barTintColor = whiteBG;
self.bottomView.barTintColor = whiteBG;
self.topView.alpha = 0.5;
self.bottomView.alpha = 0.5;
}
#pragma mark - Event Handling
- (void) cancelPressed:(UIBarButtonItem *)sender{
[self.delegate cameraViewController:self didCompleteWithImage:nil];
}
#pragma mark - Layout
- (void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
CGFloat width = CGRectGetWidth(self.view.bounds);
self.topView.frame = CGRectMake(0, self.topLayoutGuide.length, width, 44);
CGFloat yOriginOfBottomView = CGRectGetMaxY(self.topView.frame) + width;
CGFloat heightOfBottomView = CGRectGetHeight(self.view.frame) - yOriginOfBottomView;
self.bottomView.frame = CGRectMake(0, yOriginOfBottomView, width, heightOfBottomView);
self.imagePreview.frame = self.view.bounds;
self.captureVideoPreviewLayer.frame = self.imagePreview.bounds;
self.cropBox.frame = CGRectMake(0, CGRectGetMaxY(self.topView.frame), width, width);
CGFloat cameraToolbarHeight = 100;
self.cameraToolbar.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds) - cameraToolbarHeight, width, cameraToolbarHeight);
}
#pragma mark - CameraToolBarDelegate
- (void)leftButtonPressedOnToolbar:(CameraToolBar *)toolbar{
AVCaptureDeviceInput *currentCameraInput = self.session.inputs.firstObject;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
if (devices.count > 1) {
NSUInteger currentIndex = [devices indexOfObject:currentCameraInput.device];
NSUInteger newIndex = 0;
if (currentIndex < devices.count -1) {
newIndex = currentIndex + 1;
}
AVCaptureDevice *newCamera = devices[newIndex];
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:nil];
if (newVideoInput) {
UIView *fakeView = [self.imagePreview snapshotViewAfterScreenUpdates:YES];
fakeView.frame = self.imagePreview.frame;
[self.view insertSubview:fakeView aboveSubview:self.imagePreview];
[self.session beginConfiguration];
[self.session removeInput:currentCameraInput];
[self.session addInput:newVideoInput];
[self.session commitConfiguration];
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
fakeView.alpha = 0;
} completion:^(BOOL finished) {
[fakeView removeFromSuperview];
}];
}
}
}
- (void) rightButtonPressedOnToolbar:(CameraToolBar *)toolbar{
ImageLibraryViewController *imageLibraryVC = [[ImageLibraryViewController alloc] init];
imageLibraryVC.delegate = self;
[self.navigationController pushViewController:imageLibraryVC animated:YES];
}
- (void) cameraButtonPressedOnToolbar:(CameraToolBar *)toolbar {
AVCaptureConnection *videoConnection;
// #8
// Find the right connection object
for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
for (AVCaptureInputPort *port in connection.inputPorts) {
if ([port.mediaType isEqual:AVMediaTypeVideo]) {
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
// #9
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
if (imageSampleBuffer) {
// #10
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
// #11
CGSize size = self.captureVideoPreviewLayer.bounds.size;
CGRect cropRect = self.cropBox.frame;
cropRect.origin.x = (CGRectGetMinX(cropRect) + (image.size.width - CGRectGetWidth(cropRect)) / 2);
UIImage *scaledImage = [image imageByScalingToSize:size andCroppingWithRect:cropRect];
// #13
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate cameraViewController:self didCompleteWithImage:scaledImage];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:error.localizedDescription message:error.localizedRecoverySuggestion preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK button") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self.delegate cameraViewController:self didCompleteWithImage:nil];
}]];
[self presentViewController:alertVC animated:YES completion:nil];
});
}
}];
}
#pragma mark - ImageLibraryViewControllerDelegate
- (void) imageLibraryViewController:(ImageLibraryViewController *)imageLibraryViewController didCompleteWithImage:(UIImage *)image {
[self.delegate cameraViewController:self didCompleteWithImage:image];
}
@end