我一直在努力做到这一点。我有一个相机覆盖。我想让我的最终图像成为可从内置相机查看的图像的一部分。
我所做的是使 CGRect 的尺寸等于相机中的正方形。然后我尝试使用此功能对其进行裁剪。
- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
我这样称呼它
CGRect rect = CGRectMake(10, 72, 300, 300);
UIImage *realImage = [self imageByCropping:[self.capturedImages objectAtIndex:0] toRect:rect];
我得到的是方向错误的劣质图像。
::编辑::
通过 Nitin 的回答,我可以裁剪屏幕的正确部分,但问题是它裁剪了相机 View 之后的 View ,即“确认 View ”。我怀疑这是因为 Nitin 的代码使用
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
并且因为所有这一切都发生在 ViewController 中,因为 Confirmation View 的 View Controller 是执行此代码的 Controller。我将尝试用一张小 map 来解释这一点
CameraOverlay.xib(它使用这个xib来创建一个覆盖)<===== CameraOverlayViewController ---------> ConfirmationView
因此,当第一次调用 ViewController(标签栏上的按钮)时,它会打开相机(UIImagePickerController),并在其上覆盖。然后,一旦用户单击图像,图像就会显示在 ConfirmationView 上。
我认为正在发生的是
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, 1.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
这些行正在执行,当时的View是ConfirmationView。注意:我调用函数
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
方法。
最佳答案
引用 Drawing and printing Guide .
CoreGraphics 和 UIKit 的默认坐标系不同。我认为你的问题是因为这个事实。
使用这些可以帮助您解决问题
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context , 0.0, rect.size.height);
CGContextScaleCTM(context , 1.0, -1.0);
关于ios - 使用 CGRect 裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311191/