【发布时间】:2017-06-20 08:44:27
【问题描述】:
我正在使用 Avfoundation 来捕获视频,我想裁剪捕获的 UIImage 的一部分。 我正在使用两个 UIImageView。 layout
这是我创建视图的代码。
-(void)addCamToView
{
AVCaptureSession *session = [[AVCaptureSession alloc]init];
session.sessionPreset = AVCaptureSessionPresetPhoto;
AVCaptureDevice *device =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
_stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
[session addOutput:output];
[session addOutput:_stillImageOutput];
output.videoSettings =
@{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
previewLayer.frame = _imv1.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResize;
CALayer *ca_imv2 = _imv2.layer;
CALayer *ca_mainImv = _imv1.layer;
[previewLayer addSublayer:ca_mainImv];
[previewLayer addSublayer:ca_imv2];
[self.view.layer addSublayer:previewLayer];
[session startRunning];
}
当用户按下捕获按钮时,我正在运行此代码来捕获图像:
-(void) Capture: (UIImageView *)
{
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];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImage *croppedImv = [self crop:imv2.frame: image];
self.imv1.image = croppedImv;
}];
}
这是我裁剪图像的代码。我想在 UIImageView2 中提取图像的一部分
- (UIImage *)crop:(CGRect)rect :(UIImage *)img {
CGImageRef imageRef = CGImageCreateWithImageInRect(img.CGImage, rect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation: img.imageOrientation];
CGImageRelease(imageRef);
return result;
}
由于某种原因,裁剪后的图像永远不会是 UIImageView2 中的图像。我错过了什么吗?
谢谢
【问题讨论】:
标签: ios objective-c iphone uiimageview uiimage