【发布时间】:2011-12-07 07:03:02
【问题描述】:
我在 UIScrollView 中有一个 UIImageView(使用 Aspect Fill 初始化)。 用户应该使用它来调整 UIImage 的大小和位置,按一个按钮,然后他在屏幕上看到的内容将被发送到服务器,仅在原始图像坐标中。换句话说,生成的图像会比屏幕上的图像大。
到目前为止,这是我的代码的基本部分:
// 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);
它看起来已经相当接近我想要的了。原点计算至少看起来是正确的。但是,生成的图像仍然存在一些差异,我猜这来自可能图像的不同纵横比。可能我需要以某种方式将scale 添加到我的size 方程中,但我真的无法理解如何。
希望有人能帮我弄到最后两米...
[编辑]
根据第一条评论,我尝试了以下内容。但不知何故,我的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];
【问题讨论】:
-
能否请您发布您的最终解决方案?我有同样的问题
-
我有同样的问题,尝试过类似的方法,但它从来没有 100% 准确(有时 x 位置的偏移量小于应有的值)。
-
有没有人得到@Dennis 问题的最终解决方案
标签: ios resize core-graphics crop