Search code examples
iosuiscrollview

How to take screenshot of UIScrollView visible area?


How do I take a 1:1 screenshot of UIScrollView visible area? The content may be larger or smaller than UIScrollView bounds as well as half-hidden (I've implemented custom scrolling for smaller content, so it's not in the top-left corner). I've achieved desired result on simulator, but not on device itself:

-(UIImage *)imageFromCombinedContext:(UIView *)background {
      UIImage *image;
      CGRect vis = background.bounds;
      CGSize size = vis.size;
      UIGraphicsBeginImageContext(size);
      [background.layer affineTransform];
      [background.layer renderInontext:UIGraphicsGetCurrentContext()];
      image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      CGImageRef imref = CGImageCreateWithImageInRect([image CGImage], vis);
      image = [UIImage imageWithCGImage:imref];
      CGImageRelease(imref);
      return image;
}

Solution

  • I've found a solution myself - I took screenshot of the whole view and then crop it to the size and position of UIScrollView frame.

    -(UIImage *)imageFromCombinedContext:(UIView *)background 
    {
          UIImage *image;
          CGSize size = self.view.frame.size;
          UIGraphicsBeginImageContext(size);
          [background.layer affineTransform];
          [self.view.layer.layer renderInContext:UIGraphicsGetCurrentContext()];
          image = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
          CGImageRef imgRef = CGImageCreateWithImageInRect([image CGImage],background.frame);
          image = [UIImage imageWithCGImage:imref];
          CGImageRelease(imref);
          return image;
    }