从捏合/缩放状态裁剪UIImage

时间:2014-05-08 23:24:02

标签: ios uiscrollview uiimage crop

我一直在寻找一种在ScrollView中裁剪图像(imageView)的方法。我需要实现的是用户捏缩放图像(效果很好),然后只能裁剪缩放后显示在屏幕上的图像部分。换句话说,如果我有一系列的数字1到10,用户将其缩放以仅查看数字4和5,当用户点击裁剪时,我只需要在裁剪时可见的4和5的图像。我正在使用此代码...

- (UIImage *)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom
{
    CGFloat zoomReciprocal = 1.0f / zoom;
    CGRect croppedRect = CGRectMake(self.scrollView.contentOffset.x*zoom,
                                    self.scrollView.contentOffset.y*zoom,
                                    image.size.width * zoomReciprocal,
                                    image.size.height * zoomReciprocal);

    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);

    UIImage* croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];

    CGImageRelease(croppedImageRef);

    return croppedImage;
}

此方法裁剪图像,但x和y值不正确...我需要做些什么来获得裁剪区域的正确x和y?

仅供参考。我试图裁剪的图片是2200 * 3200,不确定这是否会有所不同?

1 个答案:

答案 0 :(得分:3)

我解决了!!这是针对可能遇到此问题的其他人的更新方法。

- (UIImage *)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom {
    CGFloat zoomReciprocal = 1.0f / zoom;
    CGFloat xOffset = image.size.width / self.scrollViewBackground.contentSize.width;
    CGFloat yOffset = image.size.height / self.scrollViewBackground.contentSize.height;

    CGRect croppedRect = CGRectMake(self.scrollViewBackground.contentOffset.x * xOffset,
                                    self.scrollViewBackground.contentOffset.y * yOffset,
                                    image.size.width * zoomReciprocal,
                                    image.size.height * zoomReciprocal);

    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);
    UIImage *croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];
    CGImageRelease(croppedImageRef);
    return croppedImage;

}