Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image becomes blurry when painting a Image from GraphicContext? [duplicate]

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:

enter image description here

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:

enter image description here

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?

like image 326
confile Avatar asked Apr 20 '15 12:04

confile


1 Answers

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
}
like image 179
Kevin R Avatar answered Oct 25 '22 12:10

Kevin R