I created a ViewController with a UIImageView in the storyboard. The ImageView is set to Aspect Fit
and gets a yellow background color.
Here is the photo I used for the test.
When I run my app the image appears is shown below:
There is no problem. The image looks sharp. Now I did the following in my viewDidLoad
method:
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(imageView.image!.size)
imageView.image!.drawInRect(CGRectMake(0, 0, imageView.image!.size.width, imageView.image!.size.height))
var drawedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = drawedImage
}
Here is the result:
After drawing the image from the graphic context it appears much more blurry than before.
How do I prevent images to become blurry when drawn back from graphic context?
What might be the problem, is that the image CGSize returns the size in points, not in pixels. Retina screens (all iDevice screens that are still sold) have multiple pixels per point.
Try multiplying by the screen-scaling factor or set it to 0 to be determined automatically (default is 1):
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(imageView.image!.size, imageView.opaque, 0.0)
imageView.image!.drawInRect(CGRectMake(0, 0, imageView.image!.size.width, imageView.image!.size.height))
var drawedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = drawedImage
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With