【问题标题】:Cropping Image using CGImageCreateWithImageInRect使用 CGImageCreateWithImageInRect 裁剪图像
【发布时间】:2012-10-07 15:37:55
【问题描述】:

我正在尝试实现一个 iOS 相机视图,它可以拍摄方形照片(类似于 Instagram)。我的代码出现在下面。第一部分,其中框架高度设置为等于框架宽度,按预期工作,并且为用户提供了一个正方形的视图。当我尝试使用 CGImageCreateWithImageInRect 将框架(这是一个 CGRect 属性)应用于图像数据时,稍后会出现问题。我将框架矩形与图像一起传递给此方法。但结果并没有被裁剪成正方形。相反,图像保留了 iOS 相机的原始默认尺寸。有人可以告诉我我做错了什么吗?我对 Apple 文档的理解是 CGImageCreateWithImageInRect 应该从某个起始 x/y 坐标中选择形状为 Rect 的图像区域。但这似乎没有发生。

//Set the frame size to be square shaped
UIView *view = imagePicker.view;
        frame = view.frame;
        frame.size.height = frame.size.width;
        view.frame = frame;

//Crop the image to the frame dimensions using CGImageCreateWithImageInRect
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self.popoverController dismissPopoverAnimated:true];

NSString *mediaType = [info
                       objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
    UIImage *image = [info
                      objectForKey:UIImagePickerControllerOriginalImage];

    croppedImage = (__bridge UIImage *)(CGImageCreateWithImageInRect((__bridge CGImageRef)(image), frame));

    imageView.image = croppedImage;

}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
    // Code here to support video if enabled
}
}

【问题讨论】:

    标签: iphone objective-c ios


    【解决方案1】:

    你做得对。唯一的问题是我认为您将 frame 属性设置为与选取器视图相同,因此最终大小与原始大小相同。

    尽量设置frame小于pickerView.view.frame,不等于

    看看这个

    Cropping an UIImage

    【讨论】:

    • 我尝试传递一个任意小的 CGRect 但输出有 0 字节的图像数据。我使用了 CGRect rect = CGRectMake(0, 26, 50, 50);。另外,我的原始代码将框架高度设置为等于宽度,因此小于原始大小。它本质上是一个基于 iPhone 屏幕尺寸的 320x320 正方形。
    【解决方案2】:

    您设置的框架错误。 我建议您看一下 Apple 提供的示例代码,了解如何创建您想要的内容:

    https://developer.apple.com/library/mac/#samplecode/VirtualScanner/Listings/Sources_VirtualScanner_m.html#//apple_ref/doc/uid/DTS40011006-Sources_VirtualScanner_m-DontLinkElementID_9

    看看:

    - (ICAError)startScanningWithParams:(ICD_ScannerStartPB*)pb
    

    功能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 2016-05-25
      • 2012-12-28
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多