ios - 如何在 iPhone 中捕捉相机的可见 View

标签 ios iphone objective-c avcapturesession avcapturedevice

我创建了一个 View Controller ,50% 的 View 是相机 View ,另外 50% 是按钮等。
我面临的问题是当我捕获图像时捕获了更大的图像并且我只想捕获我在 50% 的 View 中可以看到的内容。
所以它看起来像这样:
这是我在 View 中看到的:
enter image description here
这是我在拍摄后得到的图像:
enter image description here
这背后的代码是:

-(void) viewDidAppear:(BOOL)animated
{
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    CALayer *viewLayer = self.vImagePreview.view.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    [captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

    captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;
    [self.vImagePreview.view.layer addSublayer:captureVideoPreviewLayer];
    NSLog(@"Rect of self.view: %@",NSStringFromCGRect(self.vImagePreview.view.frame));
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [stillImageOutput setOutputSettings:outputSettings];

    [session addOutput:stillImageOutput];

    [session startRunning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Load camera
    vImagePreview = [[CameraViewController alloc]init];

    vImagePreview.view.frame = CGRectMake(10, 10, 300, 500);
    [self.view addSubview:vImagePreview.view];

    vImage = [[UIImageView alloc]init];
    vImage.frame = CGRectMake(10, 10, 300, 300);

    [self.view addSubview:vImage];

}

这是我尝试捕捉图像时的事件:

AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in stillImageOutput.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }

    NSLog(@"about to request a capture from: %@", stillImageOutput);
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments)
         {
             // Do something with the attachments.
             NSLog(@"attachements: %@", exifAttachments);
         }
         else
             NSLog(@"no attachments");

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         image = [[UIImage alloc] initWithData:imageData];

         UIAlertView *successAlert = [[UIAlertView alloc] init];
         successAlert.title = @"Review Picture";
         successAlert.message = @"";
         [successAlert addButtonWithTitle:@"Save"];
         [successAlert addButtonWithTitle:@"Retake"];

         [successAlert setDelegate:self];

         UIImageView *_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 10, 40, 40)];
         _imageView.image = image;
         [successAlert addSubview:_imageView];
         [successAlert show];

         UIImage *_image = [self imageByScalingAndCroppingForSize:CGSizeMake(640,480) :_imageView.image];
         NSData *idata = [NSData dataWithData:UIImagePNGRepresentation(_image)];
         encodedImage = [self encodeBase64WithData:idata];
     }];

为什么我得到的是整个摄像头 View ,如何缩小摄像头捕获的大小,以便我只能捕获在摄像头 View 中看到的内容?

最佳答案

您可以在拍摄后裁剪图像。试试这个

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

或者试试这个

- (UIImage *)crop:(CGRect)rect {
if (self.scale > 1.0f) {
    rect = CGRectMake(rect.origin.x * self.scale,
                      rect.origin.y * self.scale,
                      rect.size.width * self.scale,
                      rect.size.height * self.scale);
}

CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imageRef);
return result;
}

另请参阅此链接:Crop UIImage

关于ios - 如何在 iPhone 中捕捉相机的可见 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967343/

相关文章:

ios - Xcode:如何更改 xcode 5 中的图标?

ios - UICollectionview 和单元格

ios - 在 iPad 上禁用手写笔滚动

iphone - 向 iPhone 应用程序添加图形

iPhone - 关闭模态视图 Controller 后 - 页面顶部留有空隙

ios - AVAudioPlayerNode 同时播放多首歌曲

iphone - Storyboard和 Nib 兼容吗?

iphone - 在后台运行时响应的iPhone应用

ios - 停止仿射变换应用于 subview

ios - 在不使用UIDocumentInteractionController的情况下从iOS应用程序在Whatsapp上共享图像