我正在Swift中构建一个圆形裁剪功能。我几乎把一切都搞定了,但是当我保存裁剪的照片时,它有点模糊:
不确定这里是否可见,但在我的iPhone上我可以看到差异,轻微模糊。我没有放大超过图像的实际尺寸。我正在使用UIScrollView,最大缩放系数设置为1.0。裁剪代码为:
func didTapOk() {
let scale = scrollView.zoomScale
let newSize = CGSize(width: image!.size.width*scale, height: image!.size.height*scale)
let offset = scrollView.contentOffset
UIGraphicsBeginImageContext(CGSize(width: 240, height: 240))
let circlePath = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 240, height: 240))
circlePath.addClip()
var sharpRect = CGRect(x: -offset.x, y: -offset.y, width: newSize.width, height: newSize.height)
sharpRect = CGRectIntegral(sharpRect)
image?.drawInRect(sharpRect)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIImageWriteToSavedPhotosAlbum(finalImage, nil, nil, nil)
}
在这里,我尝试使用CGRectIntegral
来改善结果,但它似乎没有任何区别。有什么指示我可以做些什么来改善这个?
答案 0 :(得分:7)
正在发生的事情是你的作物模糊不清,因为它没有考虑你的屏幕比例(无论你是否使用视网膜显示器等)。
使用UIGraphicsBeginImageContextWithOptions(CGSize(width: 240, height: 240), true, 0)
来说明视网膜屏幕。有关如何使用此功能的详细信息,请查看here。
答案 1 :(得分:3)
我怀疑,尽管上面接受的答案对您有用,但由于屏幕比例与图像比例相同,因此只能起作用。
由于您没有从屏幕本身渲染图像(您从UIImage
渲染到另一个UIImage
),因此屏幕比例应无关紧要。
您应该在创建上下文时传递图像的比例,如下所示:
UIGraphicsBeginImageContextWithOptions(CGSize(width: 240, height: 240), false, image.scale)
答案 2 :(得分:2)
这是Swift 3中禁用任何插值的方法。
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = CGInterpolationQuality.none
此外,由于这通常用于像素绘制目的,您可能需要添加:
// Ensure the image is not drawn upside down
context?.saveGState()
context?.translateBy(x: 0.0, y: maxHeight)
context?.scaleBy(x: 1.0, y: -1.0)
// Make the drawing
context?.draw(yourImage, in: CGRect(x: 0, y: 0, width: maxWidth, height: maxHeight))
// Restore the GState of the context
context?.restoreGState()