繁体   English   中英

从转换后的UIImageView中裁剪UIImage

[英]Crop UIImage from a transformed UIImageView

我让用户从相机中捕获图像或从库中选择一个图像。 这个图像我在UIImageView显示。 用户现在可以在边界框内缩放和定位图像,就像allowsEditing设置为YES时使用UIImagePickerController allowsEditing

当用户对结果感到满意并点击Done时,我想生成一个裁剪的UIImage 使用CGImageCreateWithImageInRect时出现问题,因为这不考虑扩展。 变换应用于imageView,如下所示:

CGAffineTransform transform = CGAffineTransformScale(self.imageView.transform, newScale, newScale);
[self.imageView setTransform:transform];

使用gestureRecognizer。

我假设发生的事情是; UIImageView被缩放并移动,然后将UIViewContentModeScaleAspectFit应用于UIImage保持,当我要求它裁剪图像时,它确实如此 - 毫不关心缩放定位。 我认为这个原因是,如果我不缩放或移动图像,只需直接点击完成裁剪工作。

我裁剪图像如下:

- (UIImage *)cropImage:(UIImage*) img toRect:(CGRect)rect {

    CGFloat scale = [[UIScreen mainScreen] scale];

    if (scale>1.0) {        
        rect = CGRectMake(rect.origin.x*scale , rect.origin.y*scale, rect.size.width*scale, rect.size.height*scale);        
    }

    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.imageView.image.scale orientation:self.imageView.image.imageOrientation];
    //    UIImage *result = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
    return result;
}

从作为我主视图的子视图的视图传递cropRect(方形覆盖框,如在UIImagePickerController中)。 主UIView有一个可以缩放的UIImageView和一个显示裁剪矩形的UIView。

我怎样才能得到“你看到的就是你得到的东西”裁剪以及我必须考虑哪些因素。 或者可能是我应该实现层次结构或不同扩展的建议。

尝试一个简单的技巧。 Apple已在其网站上提供样本,以展示如何使用代码放大照片。 完成缩放后,使用图形上下文获取边界视图的帧大小,并使用该图像获取图像。 例如,Uiview包含具有缩放图像的滚动视图。 因此,滚动视图缩放,您的图像也会缩放,现在获取边界UIview的帧大小,并从中创建图像上下文,然后将其保存为新图像。 告诉我,如果这是有道理的。

干杯:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM