【问题标题】:Image crop not properly working in iOS 6.0. Working fine in simulator.图像裁剪在 iOS 6.0 中无法正常工作。在模拟器中工作正常。
【发布时间】:2012-08-30 03:45:54
【问题描述】:
- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return cropped;
}

我正在使用此代码。请给出一些解决方案。在此先感谢

【问题讨论】:

标签: iphone


【解决方案1】:

CGImageCreateWithImageInRect 无法正确处理图像方向。 网上有许多奇怪而奇妙的裁剪技术,涉及巨大的 switch/case 语句(请参阅 Ayaz 答案中的链接),但是如果您停留在 UIKit 级别并且仅使用 UIImage 本身的方法来进行绘图,所有细节都为您处理。

以下方法尽可能简单,适用于我遇到的所有情况:

- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect
{
    if (UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(rect.size,
                                               /* opaque */ NO,
                                               /* scaling factor */ 0.0);
    } else {
        UIGraphicsBeginImageContext(rect.size);
    }

    // stick to methods on UIImage so that orientation etc. are automatically
    // dealt with for us
    [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}

如果您不需要透明度,您可能需要更改 opaque 参数的值。

【讨论】:

  • 感谢您的回复。这也适用于我的旧源代码。我的问题是裁剪图像更加缩放和模糊,这个问题只发生在设备上。任何其他想法请帮助我。
  • 这听起来像是视网膜鳞片的问题。我发布的代码将在生成的图像中使用屏幕的比例,但您需要注意您传入的裁剪矩形以点为单位,而不是像素。
  • 如何传递像素。你能解释一下吗,不明白你的答案。如何处理视网膜显示裁剪问题。
  • 如果不查看更多代码,很难进一步提供帮助。如果我提供的方法不起作用,则表示您没有提供正确的裁剪矩形。
  • 我叫这个方法[self imageByCropping:cropImage toRect:CGRectMake(85, 83, 150, 150)];任何事情都对我不利。
猜你喜欢
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
相关资源
最近更新 更多