Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

Loose quality when render UIImageView in swift

I am using below code in swift to capture a UIImageView into one image. It works but the image is not as same quality as the one showing on the UIImageView. Is there a way to configure the quality when capture this image?

private func getScreenshow(imageView:UIImageView) -> UIImage{

    UIGraphicsBeginImageContext(self.imageView.frame.size)
    let context = UIGraphicsGetCurrentContext()

    imageView.layer.renderInContext(context!)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(screenShot, nil, nil, nil)
    return screenShot
}

Upvotes: 2

Views: 887

Answers (2)

Douglas Hill
Douglas Hill

Reputation: 1547

This code looks pretty weird (why don’t you just use imageView.image?) but I don’t know the full context of your use case.

As you found, the reason for the loss of quality is you are ignoring the screen’s retina scale.

Read the documentation for UIGraphicsBeginImageContext and UIGraphicsBeginImageContextWithOptions and you’ll see the former uses a ‘scale factor of 1.0’.

Upvotes: 2

Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

After some searching I figured out the issue. I use below code to replace the "UIGraphicsBeginImageContext" and it works.

UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, true, 0)

Upvotes: 2

Related Questions