ios - 如何在 'aspect fit' 模式下将 UIImageView 裁剪为新的 UIImage?

标签 ios uiimageview uiimage

enter image description here

我想通过裁剪 UIImageView 中的图像来创建一个新的 UIImage。例如在上图中,我想要一个新的 UIImage 绿色轮廓区域。我找到了执行此操作的代码,通常它看起来像这样(作为 UIImage 类别):

- (UIImage *)croppedImage:(CGRect)bounds {
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return croppedImage;
}

很有道理。但是,我的 UIImageView 处于 contentMode 'aspect fit'。似乎这使 CGImageCreateWithImageInRect 的 CGRect 计算变得复杂,我一直无法找出正确的解决方案。

我想我需要对绿色矩形应用与图像相同的变换吗?

另外:我在这里发现了另一个问题(How to know the image size after applying aspect fit for the image in an UIImageView),它似乎显示了一种获取尺寸的蛮力方式,但我仍然不确定它如何适应裁剪情况。

有什么想法吗?

编辑:在我的例子中,我确实在 UIImageView 的叠加 View 中绘制了一个如上所示的正方形。因此,当我意识到我正在裁剪 UIImage(在 UIImageView 内)时,我需要以某种方式更改绿色 CGRect,使其“匹配”应用“纵横比匹配”时完成的转换。例如,如果我让我的 UIImageView 处于“左上角”模式,那么一切正常,因为底层 UIImage 和 UIImageView 之间存在 1:1 的映射。 “左上角”模式的问题是整个图像并不总是显示,因为它可能比我的 UIImageView 大。

最佳答案

基于我的 other answer对于类似的问题,我已经为 UIImageView 类别编写了这个方法:

-(CGRect) cropRectForFrame:(CGRect)frame
{
    NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit");

    CGFloat widthScale = self.bounds.size.width / self.image.size.width;
    CGFloat heightScale = self.bounds.size.height / self.image.size.height;

    float x, y, w, h, offset;
    if (widthScale<heightScale) {
        offset = (self.bounds.size.height - (self.image.size.height*widthScale))/2;
        x = frame.origin.x / widthScale;
        y = (frame.origin.y-offset) / widthScale;
        w = frame.size.width / widthScale;
        h = frame.size.height / widthScale;
    } else {
        offset = (self.bounds.size.width - (self.image.size.width*heightScale))/2;
        x = (frame.origin.x-offset) / heightScale;
        y = frame.origin.y / heightScale;
        w = frame.size.width / heightScale;
        h = frame.size.height / heightScale;
    }
    return CGRectMake(x, y, w, h);
}

您可以传入绿色矩形的框架(假设它是 ImageView 的 subview )并获取裁剪矩形以裁剪 UIImage。请注意,它仅适用于“纵横比”模式!我还没有测试过。所以,告诉我它是否有效!

关于ios - 如何在 'aspect fit' 模式下将 UIImageView 裁剪为新的 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859717/

相关文章:

iOS Storyboard - 导航 Controller 不工作

ios - 在上下文上绘图时在 UIImage 上应用 CATransform3D

java - 带有 4 个项目的 GridView android

c++ - 从 cvMat 转换为 UIImage 会改变图像

ios - Xcode Storyboard textview 错误在中间被切断

ios - ITMS-90809 : Deprecated API Usage -- Apple will stop accepting submissions of apps that use UIWebView APIs

ios - 在 UITextView 中向 NSString 添加外部描边

ios - 如何在 iOS 中创建图像 slider ?

ios - 如何在 Image.xcassets 中为图像构建 NSURL?

ios - 将 UIImage 转换为数据 URI