在UIScrollView问题中裁剪缩放图像

Dee*_*kur 0 zoom objective-c uiscrollview uiimage ios

完成此链接后,我的代码问题是输出图像无法设置正确的x和y值,因为裁剪后的图像似乎在结果图像中有0和0,无论我在哪里缩放(或计算滚动偏移的位置) .这是我尝试过的.

- (IBAction)crop:(id)sender
{

    float zoomScale = 1.0f / [self.scroll zoomScale];

    CGRect rect;
    NSLog(@"contentOffset is :%f,%f",[self.scroll contentOffset].x,[self.scroll contentOffset].y);
    rect.origin.x = self.scroll.contentOffset.x * zoomScale;
    rect.origin.y = self.scroll.contentOffset.y * zoomScale;
    rect.size.width = self.scroll.bounds.size.width * zoomScale;
    rect.size.height = self.scroll.bounds.size.height * zoomScale;

    UIGraphicsBeginImageContextWithOptions( CGSizeMake(rect.size.width, rect.size.height),
                                           NO,
                                           0.);

    NSLog(@"rect offset is :%f,%f",rect.origin.x,rect.origin.y);
    CGPoint point = CGPointMake(-rect.origin.x, -rect.origin.y); **//even though above NSLog have some values, but output image is unable to set proper x and y values as cropped image seems to have 0 and 0 in the resultant image.**
    [[self.imagV image] drawAtPoint:point
                          blendMode:kCGBlendModeCopy
                              alpha:1];
    self.croppedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

DTImageViewController *imageViewController = [[DTImageViewController alloc] initWithNibName:@"DTImageViewController" bundle:nil];
    imageViewController.image = self.croppedImage;
    [self.navigationController pushViewController:imageViewController animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*per 5

类似的代码已经发布但只是采取整个UIScrollView边界而不通过CGRect

-(void)takeScreenShotOfScrollView
{
    UIGraphicsBeginImageContextWithOptions(scrollView.bounds.size, YES, [UIScreen mainScreen].scale);
    CGPoint offset = scrollView.contentOffset;
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y);

    [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    img = [SDImageHelper imageWithImage:img_image scaledToSize:CGSizeMake(769, 495)];
}
Run Code Online (Sandbox Code Playgroud)

奖金:

裁剪方法

+(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
Run Code Online (Sandbox Code Playgroud)