Search code examples
swiftuiscrollviewuigraphicscontext

Extra white space when get visible content of UIScrollView


There is a UIImageView inside a UIScrollView which user can scale it down and up and then save it:

enter image description here

The area under the navigation bar and top of the tab bar is UIScrollView frame.

When user hits Done, image will be save in camera roll. It's what saved there (Photos App): enter image description here

I have no idea what is this empty space in the saved image.

It's my code to save the image:

UIGraphicsBeginImageContextWithOptions(scrollView.frame.size, false, 0.0)
            let rect = CGRectMake(0, scrollView.frame.origin.y, scrollView.frame.size.width, scrollView.frame.size.height)
            self.view.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            let imageData = UIImageJPEGRepresentation(image, 1)
            let compressedJPGImage = UIImage(data: imageData!)
            UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)

What I want to save is exactly the visible region of UIScrollView.


Solution

  • I had to use CGContextTranslateCTM() to translate the rectangle:

        let screenRect: CGRect = scrollView.bounds
        UIGraphicsBeginImageContext(screenRect.size)
        let ctx: CGContextRef = UIGraphicsGetCurrentContext()!
        CGContextTranslateCTM(ctx,0,-scrollView.frame.origin.y)
        UIColor.blackColor().set()
        CGContextFillRect(ctx, screenRect)
            view.layer.renderInContext(ctx)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()