旋转图像变形和模糊?

时间:2015-04-20 17:41:40

标签: ios iphone swift core-graphics

我使用图片视图:

@IBOutlet weak var imageView: UIImageView!

绘制图像以及另一个已旋转的图像。事实证明旋转的图像质量非常差。在下图中,黄色框中的眼镜未旋转。红色框中的眼镜旋转了4.39度。

enter image description here

以下是我用来绘制眼镜的代码:

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)

如何旋转和涂抹眼镜而不会降低质量或使图像失真?

2 个答案:

答案 0 :(得分:3)

您应该使用UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)来创建初始上下文。作为0.0传递scale将默认为当前屏幕的比例(例如,iPhone 6上的2.0和iPhone 6 Plus上的3.0

请参阅UIGraphicsBeginImageContext()上的这条说明:

  

此函数等效于调用UIGraphicsBeginImageContextWithOptions函数,其中opaque参数设置为NO,比例因子为1.0。

答案 1 :(得分:1)

正如其他人所指出的那样,您需要设置上下文以允许视网膜显示。

除此之外,您可能希望使用大于目标显示大小的源图像并将其缩小。 (2X目标图像的像素尺寸将是一个很好的起点。)

旋转到奇数角度是破坏性的。图形引擎必须将源像素网格映射到不排列的不同网格上。源图像中的完美直线在目标图像等中不再是直的。图形引擎必须进行一些插值,并且源像素可能分布在目标图像中的几个像素或小于整个像素上。

通过提供更大的源图像,您可以为图形引擎提供更多信息。它可以更好地将这些源像素切片和切块到目标像素网格中。

相关问题