Search code examples
iosswiftuiscrollviewuiimageviewuiimage

Get Visible portion Image from UIimageView in Scrollview


I have a UIImageView in a UIScrollView in which can be zoomed in and out. Now, after the user has selected the specific content to be zoomed in, I want to crop that part of image present on the scrollview and get it in the form on UIImage.

For that I am using

extension UIScrollView {

var snapshotVisibleArea: UIImage? {
    UIGraphicsBeginImageContext(bounds.size)
    UIGraphicsGetCurrentContext()?.translateBy(x: -contentOffset.x, y: -contentOffset.y)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

}

But when I implement this, the quality of the image get extremely degraded. Even If I use a 4K image, the final product looks like a 360p resolution.

This logic is just basic capturing of the screen content.

I know there can be a better way but I am not able to find a solution. Any help is highly appreciated.


Solution

  • You can try this:

    let context:CGContext = UIGraphicsGetCurrentContext()!
    context.interpolationQuality = .high
    

    Also I'm not sure but image quality could be improve if you initialize image context with this code: UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)