【问题标题】:Crop Image using CGRect使用 CGRect 裁剪图像
【发布时间】:2013-08-21 02:18:02
【问题描述】:

我一直在尝试这样做。我有一个相机覆盖。我想让我的最终图像成为可从内置相机查看的图像的一部分。 我所做的是使 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 的回答,我可以裁剪屏幕的正确部分,但问题是它裁剪了相机视图之后的视图,即“确认视图”。我怀疑这是因为 Nitin 的代码使用了

UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();

因为所有这一切都发生在 ViewController 中,因为 Confirmation View 的 View Controller 是执行此代码的 Controller。我将尝试用一张小地图来解释这一点

CameraOverlay.xib(它使用这个xib来创建一个覆盖) 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 方法。

【问题讨论】:

    标签: ios objective-c uiimage camera-overlay


    【解决方案1】:

    请参考Drawing and printing Guide

    CoreGraphics 和 UIKit 的默认坐标系不同。我认为你的问题是因为这个事实。

    使用这些可能会帮助您解决问题

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context , 0.0, rect.size.height);
    CGContextScaleCTM(context , 1.0, -1.0);
    

    【讨论】:

    • 感谢您的回答。我认为这段代码与我对 Nitin 的回答有同样的问题。请你看一下编辑吗?
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 2021-11-18
    • 2015-10-28
    • 2017-05-22
    • 1970-01-01
    • 2016-05-25
    • 2012-12-28
    • 1970-01-01
    相关资源
    最近更新 更多