gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:19:15 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的应用程序,将相机叠加层与在 UIImagePicker 中拍摄的照片相结合。在这个例子中,我想将熊耳朵的叠加 View 与照片结合起来。

- (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) 处,而是位于最终图像的中间。我不确定为什么会这样。我只是想让它像在相机 View 中一样覆盖图像。任何想法为什么会这样?谢谢

最佳答案

我认为图像居中,因为您在两个图像的 drawInRect 方法中使用相同的矩形大小。尝试将水印图像的大小从backgroundImage.size更改为watermarkImage.size:

[watermarkImage drawInRect:CGRectMake(0, 0, watermarkImage.size.width, watermarkImage.size.height)];

编辑:

要为水印图像设置正确的尺寸,您需要找到缩放尺寸 - 预览中的图像与最终图像的尺寸差异。您可以通过将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)];

希望对您有所帮助。

关于ios - 使用 UIGraphics 组合两个图像时遇到问题,图像位置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com