如何捕获 Scrollview 内的缩放 UIImageView 进行裁剪?

2024-05-07

问题: 缩小图像进行裁剪就可以了。 放大图像后进行裁剪会显示应有的图像上方的图像。 我在那里的 yOffset 是因为我想要的裁剪方块从滚动视图的下方开始。

Code:

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];

我在做什么导致图像在缩放时获得错误的高度?


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];
}

加载原始图像:

缩放图像:

最终捕获图像

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何捕获 Scrollview 内的缩放 UIImageView 进行裁剪? 的相关文章

随机推荐