2014-03-14 5 views
1

바코드는 읽을 수 있지만 화면의 스냅 샷을 얻을 수 없습니다. getScreenImage 함수는 흰색 화면을 가져옵니다. 카메라보기를 볼 수있는 스크린을 포함한 스크린 샷을 어떻게 얻을 수 있습니까? 고맙습니다.하얀색 화면 캡처

@interface igViewController() <AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate> 
{ 
    AVCaptureSession *_session; 
    AVCaptureDevice *_device; 
    AVCaptureDeviceInput *_input; 
    AVCaptureMetadataOutput *_output; 
    AVCaptureVideoPreviewLayer *_prevLayer; 

    UIView *_highlightView; 
    UILabel *_label; 
    UIImage *img; 

} 
@end 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    _highlightView = [[UIView alloc] init]; 
    _highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin; 
    _highlightView.layer.borderColor = [UIColor greenColor].CGColor; 
    _highlightView.layer.borderWidth = 3; 
    [self.view addSubview:_highlightView]; 

    _label = [[UILabel alloc] init]; 
    _label.frame = CGRectMake(0, self.view.bounds.size.height -100, self.view.bounds.size.width, 100); 
    _label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin; 
    _label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65]; 
    _label.textColor = [UIColor whiteColor]; 
    _label.textAlignment = NSTextAlignmentCenter; 


    //[_label addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL]; 
    [self.view addSubview:_label]; 

    _session = [[AVCaptureSession alloc] init]; 
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 
    NSError *error = nil; 

    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error]; 
    if (_input) { 
     [_session addInput:_input]; 
    } else { 
     NSLog(@"Error: %@", error); 
    } 

    _output = [[AVCaptureMetadataOutput alloc] init]; 
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; 
    [_session addOutput:_output]; 

    _output.metadataObjectTypes = [_output availableMetadataObjectTypes]; 

    _prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session]; 
    _prevLayer.frame = self.view.bounds; 
    _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; 
    [self.view.layer addSublayer:_prevLayer]; 
    [_session startRunning]; 

    [self.view bringSubviewToFront:_highlightView]; 
    [self.view bringSubviewToFront:_label]; 
} 
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection 
{ 
    CGRect highlightViewRect = CGRectZero; 
    AVMetadataMachineReadableCodeObject *barCodeObject; 
    detectionString = nil; 
    NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, 
      AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, 
      AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode]; 

    for (AVMetadataObject *metadata in metadataObjects) { 

     for (NSString *type in barCodeTypes) { 
      if ([metadata.type isEqualToString:type]) 
      { 
       barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata]; 
       highlightViewRect = barCodeObject.bounds; 
       detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue]; 
       break; 
      } 
     } 

     _highlightView.frame = highlightViewRect; 
     if (detectionString != nil) 
     { NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil]; 
      [self getScreenImage]; 
      _label.text = detectionString; 
      [self performSelector:@selector(changeText) withObject:nil afterDelay:2.0]; 
      break; 
     } 
    } 

    if(detectionString!=nil){ 
     [MainViewController setResultTexts:detectionString img:img]; 
     detectionString=nil; 
     [self dismissViewControllerAnimated:YES completion:nil]; 
     [_session stopRunning]; 

    } 
} 
CGImageRef UIGetScreenImage(void); 
-(void)getScreenImage{ 
    if(detectionString!=nil){ 
    CGImageRef screen = UIGetScreenImage(); 
    img = [UIImage imageWithCGImage:screen]; 
    CGImageRelease(screen); 
    } 
} 

편집 :

이 작동합니다. 그러나 세션에 대한 출력을보다 신속하게 변경해야합니다. 이미지를 캡처하기 위해 세션이 변경되기 때문입니다. 따라서 화면이 잠시 사라집니다. 그리고 % 50 불투명도의 화면 만 얻습니다. This link은 도움을받는 곳입니다. 이제 어떻게 100 % 불투명 스크린 샷을 얻을 수 있습니까?

_highlightView.frame = highlightViewRect; 
     if (detectionString != nil) 
     { 
      **[_session removeOutput:_output]; 
      [_session addOutput:_stillImageOutput];** 
      _label.text = detectionString; 
      **[self captureNow];** 
      [self performSelector:@selector(changeText) withObject:nil afterDelay:1.0]; 
      break; 
     } 

-(void)captureNow { 
    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) 
    { 
     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; 
     img = [[UIImage alloc] initWithData:imageData]; 
    }]; 

} 
+0

는'snapshotViewAfterScreenUpdates를 사용합니다. – n00bProgrammer

+0

그냥 모든 요소가 포함 된 화면을 캡처해야합니까? –

+0

@Charan : 예. 그것은 내가 필요한 것입니다. – user3309441

답변

0

내가 AVCaptureStillImageOutput을 사용하고 근무로 대체 내가 스크린 샷과 같이있는 ScrollView에있는 모든 내용을지고있어 contentScrollview 내있는 ScrollView입니다 여기를보십시오. ``resizableSnapshotViewFromRect : afterScreenUpdates : withCapInsets`, 또는`drawViewHierarchyInRect : afterScreenUpdates : '배포 대상이 나중에 아이폰 OS 7.x 및 경우

-(void)captureNow { 
     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; 
      } 
     } 


     [_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) 
     { 
      NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; 
      img = [[UIImage alloc] initWithData:imageData]; 
//I used image in another viewcontroller 
      [MainViewController setResultTexts:str img:img]; 
      [MainViewController set_from_view:0 scanner:1]; 
      [self dismissViewControllerAnimated:YES completion:nil]; 

     }]; 

    } 
-1

당신이보기 객체

- (UIImage *) imageFromViewIniOS7 
{ 
UIImage* image = nil; 
UIGraphicsBeginImageContext(contentScrollview.contentSize); 
{ 
    CGPoint savedContentOffset = contentScrollview.contentOffset; 
    CGRect savedFrame = contentScrollview.frame; 

    contentScrollview.contentOffset = CGPointZero; 
    contentScrollview.frame = CGRectMake(0, 0, contentScrollview.contentSize.width, contentScrollview.contentSize.height); 
    if ([[NSString versionofiOS] intValue]>=7) 
    { 
     [contentScrollview drawViewHierarchyInRect:contentScrollview.bounds afterScreenUpdates:YES]; 

    } 
    else 
    { 
     [contentScrollview.layer renderInContext: UIGraphicsGetCurrentContext()]; 

    } 
    image = UIGraphicsGetImageFromCurrentImageContext(); 

    contentScrollview.contentOffset = savedContentOffset; 
    contentScrollview.frame = savedFrame; 
} 
UIGraphicsEndImageContext(); 


return image; 
} 
+0

작동하지 않습니다. 나는 내가 원하는 화면을 확인했다. AVCaptureVideoPreviewLayer입니다. 그리고 renderInContext를 위해 그것의 레이어에 접근 할 수 없다. 나는 그것이 스크린 샷이 항상 흰색 인 이유라고 생각합니다. – user3309441

+0

50 % 50 % 효과가 있습니다. 수정 된 질문을 확인해 주시겠습니까? – user3309441