如何在Scrollview内捕获缩放的UIImageView进行

如何在Scrollview内捕获缩放的UIImageView进行

本文介绍了如何在Scrollview内捕获缩放的UIImageView进行裁剪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:图像缩小时进行裁剪是可以的.放大图像进行裁剪显示的图像超出了应有的水平.之所以存在yOffset,是因为我想要的裁剪正方形从滚动视图所在的位置开始.

Problem:Cropping with the image zoomed out is fine.Cropping with the image zoomed in is showing the image above what is should be.The yOffset I have in there is because the crop square I want starts below where the scrollview does.

代码:

CGRect rect;
float yOffset = 84;
rect.origin.x = floorf([scrollView contentOffset].x * zoomScale);
rect.origin.y = floorf(([scrollView contentOffset].y + yOffset) * zoomScale);
rect.size.width = floorf([scrollView bounds].size.width * zoomScale);
rect.size.height = floorf((320 * zoomScale));

if (rect.size.width > 320) {
    rect.size.width = 320;
}

if (rect.size.height > 320) {
    rect.size.height = 320;
}

CGImageRef cr = CGImageCreateWithImageInRect([[imageView image] CGImage], rect);

UIImage *img = imageView.image; //[UIImage imageWithCGImage:cr];

UIGraphicsBeginImageContext(rect.size);

// translated rectangle for drawing sub image
CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, 320.0f, 320.0f);
NSLog(@"drawRect: %@", NSStringFromCGRect(drawRect));
NSLog(@"rect: %@", NSStringFromCGRect(rect));

// draw image
[img drawInRect:drawRect];

// grab image
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

CGImageRelease(cr);

[self.delegate imageCropper:self didFinishCroppingWithImage:cropped];

我该怎么办,导致缩放时图像的高度错误?

What am I doing that is causing the image to get the wrong height when zooming?

推荐答案

UIImage* imageFromView(UIImage* srcImage, CGRect* rect)
{
    CGImageRef cr = CGImageCreateWithImageInRect(srcImage.CGImage, *rect);
    UIImage* cropped = [UIImage imageWithCGImage:cr];

    CGImageRelease(cr);
    return cropped;
}
-(void) doneEditing
{
    //Calculate the required area from the scrollview
    CGRect visibleRect;
    float scale = 1.0f/scrollView.zoomScale;
    visibleRect.origin.x = scrollView.contentOffset.x * scale;
    visibleRect.origin.y = scrollView.contentOffset.y * scale;
    visibleRect.size.width = scrollView.bounds.size.width * scale;
    visibleRect.size.height = scrollView.bounds.size.height * scale;


    FinalOutputView* outputView = [[FinalOutputView alloc] initWithNibName:@"FinalOutputView" bundle:[NSBundle mainBundle]];
    outputView.image = imageFromView(imageView.image, &visibleRect);

    [self.navigationController pushViewController:outputView animated:YES];
    [outputView release];
}

加载原始图片:

缩放图像:

最终捕获图像

这篇关于如何在Scrollview内捕获缩放的UIImageView进行裁剪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:38