2014-05-08 70 views
0

我一直在四处寻找找到一种方法来裁剪图像(imageView)内滚动查看。我需要在这里实现的是用户捏放大图像,(这是很好的工作),然后能够仅缩放在缩放后显示在屏幕上的图像部分。所以换句话说,如果我有一系列的数字1到10,用户缩放它只能看到数字4和5,当用户点击裁剪时,我只需要在裁剪时可见的4和5的图像。我使用这个代码...裁剪UIImage从捏/缩放状态

- (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,不知道这是否会有所作为?

回答

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; 

}