调整UIImage大小以保持Swift的图像质量

时间:2019-03-16 04:06:03

标签: swift image resize blurry

我已经使用UIGraphicsGetCurrentContext从UIView创建了图像。它工作正常,但是当我将图像调整为较大尺寸时,图像质量会模糊不清。调整大小时是否可以保持质量?我尝试了很多方法,但是没有用。  -代码图片:

func image(with view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)

        context.setAllowsAntialiasing(true)
        context.setShouldAntialias(true)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        return image

    }
    return nil

}

我用来调整大小的代码,UIImage的此扩展

func resizedImage(newSize: CGSize) -> UIImage {
    // Guard newSize is different
    guard self.size != newSize else { return self }
     let aspect_ratio = self.size.width / self.size.height

    var image_w = newSize.height * aspect_ratio

    let finalSize = CGSize(width: image_w, height: newSize.height) 
    UIGraphicsBeginImageContextWithOptions(finalSize, false, 0.0)
    self.draw(in: CGRect(x: 0, y: 0, width: (CGFloat)(finalSize.width), height: (CGFloat)(newSize.height)))
    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}

和示例图片:image 谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下:

extension UIImage {
    func resizeImage(targetSize: CGSize) -> UIImage {
        let size = self.size
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
  }
}