Is image rotation distorted and blurred?

I use image view:

@IBOutlet weak var imageView: UIImageView! 

to draw an image, as well as another image that has been rotated. It turns out that the rotated image has very poor quality. In the following image, the glasses in the yellow box do not rotate. The glasses in the red box are rotated 4.39 degrees.

enter image description here

Here is the code I use to draw the glasses:

 UIGraphicsBeginImageContext(imageView.image!.size) imageView.image!.drawInRect(CGRectMake(0, 0, imageView.image!.size.width, imageView.image!.size.height)) var drawCtxt = UIGraphicsGetCurrentContext() var glassImage = UIImage(named: "glasses.png") let yellowRect = CGRect(...) CGContextSetStrokeColorWithColor(drawCtxt, UIColor.yellowColor().CGColor) CGContextStrokeRect(drawCtxt, yellowRect) CGContextDrawImage(drawCtxt, yellowRect, glassImage!.CGImage) // paint the rotated glasses in the red square CGContextSaveGState(drawCtxt) CGContextTranslateCTM(drawCtxt, centerX, centerY) CGContextRotateCTM(drawCtxt, 4.398 * CGFloat(M_PI) / 180) var newRect = yellowRect newRect.origin.x = -newRect.size.width / 2 newRect.origin.y = -newRect.size.height / 2 CGContextAddRect(drawCtxt, newRect) CGContextSetStrokeColorWithColor(drawCtxt, UIColor.redColor().CGColor) CGContextSetLineWidth(drawCtxt, 1) // draw the red rect CGContextStrokeRect(drawCtxt, newRect) // draw the image CGContextDrawImage(drawCtxt, newRect, glassImage!.CGImage) CGContextRestoreGState(drawCtxt) 

How can I rotate and draw glasses without losing quality or getting a distorted image?

+5
source share
2 answers

You must use UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) to create the original context. A transfer of 0.0 as the default scale scales for the current screen (for example, 2.0 on the iPhone 6 and 3.0 on the iPhone 6 Plus).

See this note at UIGraphicsBeginImageContext() :

This function is equivalent to calling the UIGraphicsBeginImageContextWithOptions function with an opaque parameter set to NO and a scale factor of 1.0.

+3
source

As others have pointed out, you need to customize your context so that retinas can be displayed.

In addition, you can use a source image larger than the target display size and scale it. (2X pixel dimensions of the target image would be a good place to start.)

Rotating at odd angles is destructive. The graphics engine should display a grid of source pixels on another grid, where they do not line up. Perfectly straight lines in the source image are no longer straight in the target image, etc. The graphics engine must do some interpolation, and the source pixel can be distributed over several pixels or less than the full pixel in the target image.

By providing a larger source image, you give the graphics engine more information to work with. It can better crop and crop these source pixels into the target pixel grid.

+1
source

All Articles