我正在尝试制作一个简单的应用,它将相机叠加层与UIImagePicker中拍摄的照片相结合。在这个例子中,我想将熊耳的叠加视图与照片结合起来。
- (IBAction)pushTakePhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
//create overlay UIView
UIImage *bearEars = [UIImage imageNamed:@"bearEars"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:bearEars];
UIView *camerOverlayView = [[UIView alloc] initWithFrame:imageView.frame];
[camerOverlayView addSubview:imageView];
[picker setCameraOverlayView:camerOverlayView];
[self presentViewController:picker animated:YES completion:NULL];
}
上面的代码创建了叠加层,这很好用。下面的代码组合了图像:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
//first we flip the image
UIImage * flippedImage = [UIImage imageWithCGImage:chosenImage.CGImage scale:chosenImage.scale orientation:UIImageOrientationLeftMirrored];
chosenImage=flippedImage;
//now we need to add the ears
//get pics
UIImage *backgroundImage = chosenImage;
UIImage *watermarkImage = [UIImage imageNamed:@"bearEars"];
//start a workspace
UIGraphicsBeginImageContext(backgroundImage.size);
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
//position seems off for some reason
[watermarkImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
chosenImage=result;
self.finalImageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
当我组合图像时,但是bearEars叠加层不是位于(0,0),而是位于最终图像的中间。我不确定为什么会这样。我只是希望它像在相机视图中一样覆盖图像。任何想法为什么会这样?感谢
答案 0 :(得分:1)
我认为图像居中是因为您在drawInRect方法中为两个图像使用相同的rect尺寸。 尝试将backgroundImage.size的大小更改为watermarkImage的watermarkImage.size:
[watermarkImage drawInRect:CGRectMake(0, 0, watermarkImage.size.width, watermarkImage.size.height)];
编辑:
要为watermarkImage执行正确的大小,您需要找到缩放大小 - 与最终图像的预览中的图像大小不同。您可以通过将backgroundImage的宽度除以self.view
的宽度来实现CGFloat scale = backgroundImage.size.width / self.view.frame.size.width;
然后你可以在绘制watermarkImage期间使用这个值:
[watermarkImage drawInRect:CGRectMake(0, 0, watermarkImage.size.width * scale, watermarkImage.size.height * scale)];
希望它有所帮助。