根据UIScrollView中的视口剪裁UIImage

我在UIScrollView里有一个UIImageView(用Aspect Fill初始化)。 用户将使用它来调整和定位一个UIImage到他的喜欢,按一个button,然后确切地说,他在屏幕上看到的将被发送到服务器,只在原来的图像坐标。 换句话说,生成的图像会比屏幕上的图像大。

以下是我的代码到目前为止的主要部分:

// select the original CGFloat imageRatio = self.imageView.image.size.width / self.imageView.image.size.height; CGFloat viewRatio = self.imageView.frame.size.width / self.imageView.frame.size.height; CGFloat scale; // get the scale factor of the image being "aspect-filled" if(imageRatio < viewRatio) { scale = self.imageView.image.size.width / self.imageView.frame.size.width; } else { scale = self.imageView.image.size.height / self.imageView.frame.size.height; } // get the cropping origin in the image's original coordinates CGFloat originX = self.imageScrollView.contentOffset.x * scale; CGFloat originY = self.imageScrollView.contentOffset.y * scale; CGPoint origin = CGPointMake(originX, originY); // get the cropping size in the image's original coordinates CGFloat width = self.imageView.image.size.width / self.imageScrollView.zoomScale; CGFloat height = self.imageView.image.size.height / self.imageScrollView.zoomScale; CGSize size = CGSizeMake(width, height); // create the new image from the original one CGRect imageRect = CGRectMake(origin.x, origin.y, size.width, size.height); struct CGImage *croppedCGImage = CGImageCreateWithImageInRect(self.imageView.image.CGImage, imageRect); 

它已经看起来非常接近我想要的。 起源计算似乎至less是正确的。 然而,由此产生的图像仍然存在一些差异,我猜想是来自于可能图像的不同纵横比。 也许我需要在某种程度上给我的size方程式添加scale ,但是我严肃地说,不能把我的脑袋包裹起来。

希望有人能帮我拿到最后两米…

[编辑]

根据第一条评论,我尝试了以下内容。 但不知何故,我的targetFrame始终与scrollFrame相同。 晚上对我来说太晚了吗?

 CGFloat zoom = self.imageScrollView.zoomScale; // the full image resolution CGRect fullImageFrame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height); UIView *fullImageView = [[[UIView alloc] initWithFrame:fullImageFrame] autorelease]; // the theoretical size of the image on the screen CGRect previewImageFrame = CGRectMake(0, 0, self.imageView.frame.size.width * zoom, self.imageView.frame.size.height * zoom); UIView *previewImageView = [[[UIView alloc] initWithFrame:previewImageFrame] autorelease]; // the excerpt of previewImageFrame really visible CGRect scrollFrame = CGRectMake(self.imageScrollView.contentOffset.x, self.imageScrollView.contentOffset.y, self.imageScrollView.frame.size.width, self.imageScrollView.frame.size.height); // that excerpt transferred to the full resolution image's coordinates CGRect targetFrame = [fullImageView convertRect:scrollFrame fromView:previewImageView]; 

你不妨探索一下:

 (CGRect)convertRect:(CGRect)rect toView:(UIView *)view 

这个和其他类似的方法可以让你根据在一个超级视图中的位置而不是它最初的意图或定位的视图来调整它的坐标系。