0
votes

I am using AV Foundation for a photo app. I have setup a preview layer that takes up the top half of the screen using this code:

[_previewLayer setFrame:CGRectMake(0, 0, rootLayer.bounds.size.width, rootLayer.bounds.size.height/2)];

Once the user captures the image, I rotate it so it's in the correct portrait orientation (since iOS likes to default images to landscape), and then I create a new sub layer and set it's contents property to the captured image. This makes the image display as the new layer on the top half of the screen.

The only problem is the image looks stretched and after doing research I learned that you need to crop the captured image, and I am having trouble getting my crop to work properly after trying for several hours.

Hopefully someone can recommend the correct crop code that I need. I just want to crop the captured image so that it is exactly what the user was seeing in the preview layer as they were taking the photo.

Here is my image capture code:

-(IBAction)stillImageCapture {

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 imageDataSampleBuffer, NSError *error) {

    if(imageDataSampleBuffer) {



        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];


        UIImage *image = [[UIImage alloc]initWithData:imageData];


        image = [self rotate:image andOrientation:image.imageOrientation];


        CALayer *subLayer = [CALayer layer];


        CGImageRef imageRef = image.CGImage;


        subLayer.contents = (id)[UIImage imageWithCGImage:imageRef].CGImage;


        subLayer.frame = _previewLayer.frame;


        [_previewLayer addSublayer:subLayer];


    }

}];


}
1

1 Answers

0
votes

My advice is to not about how you got the image. Get things represented as UIImages first, without manipulation, then have handy a library of transformations that operate on UIImages. You can start with the accepted answer on this one for cropping.