使用 UIGraphics 组合两个图像时遇到问题,图像定位不正确

Having trouble combining two images using UIGraphics, images not correctly positioned

我正在尝试制作一个简单的应用程序,将相机叠加层与在 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) 处,而是位于最终图像的中间。我不确定为什么会这样。我只是想让它像在相机视图中一样覆盖图像。任何想法为什么会这样?谢谢

我认为图像居中是因为您在两个图像的 drawInRect 方法中使用了相同的矩形大小。 尝试将 watermarkImage 的大小从 backgroundImage.size 更改为 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)];

希望对您有所帮助。