pj4*_*533 8 uiimageview uiimage ios

我想通过在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计算变得复杂,我无法找到正确的解决方案.
我想我需要像对图像一样对绿色矩形应用相同的变换?
另外:我在这里发现了另一个问题(如何在UIImageView中应用适合图像的方面后知道图像大小),这似乎显示了获得大小的蛮力方式,但我仍然不确定如何适应种植情况.
有任何想法吗?
编辑:在我的情况下,我确实有一个如上所示的正方形在UIImageView的叠加视图中绘制.因此,当我意识到我正在裁剪UIImage(在UIImageView中)时,我需要以某种方式更改绿色CGRect,使其"匹配"应用"纵横比较"时完成的转换.例如,如果我将UIImageView保留在"左上角"模式,那么一切正常,因为底层UIImage和UIImageView之间存在1:1的映射."左上角"模式中的问题是整个图像并不总是显示,因为它可能比我的UIImageView更大.
Fel*_*lix 10
基于我对类似问题的其他答案,我已经为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);
}
您可以传入绿色矩形的框架(假设它是图像视图的子视图)并将裁剪矩形返回以裁剪UIImage.请注意,它仅适用于"纵横比"模式!我没有测试过它.那么,告诉我它是否有效!
| 归档时间: | 
 | 
| 查看次数: | 16573 次 | 
| 最近记录: |