UIImage调整大小

时间:2018-03-17 10:19:51

标签: ios swift uiimageview uiimage

我有这样的图像:

Have a look at this image

并且我想将此图片调整为特定宽度:让200px ,其中高度也应该计算。 (因此图像应保持其宽高比例)

这是我到目前为止所得到的:

extension UIImage {
    func resize(newSize1: CGSize) -> UIImage {
        let size = self.size
        let widthRatio  = newSize1.width  / size.width
        let heightRatio = newSize1.height / size.height

        var newSize2: CGSize
        if(widthRatio > heightRatio) {
            newSize2 = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize2 = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }
        let rect = CGRect(x: 0, y: 0, width: newSize2.width, height: newSize2.height)
        UIGraphicsBeginImageContextWithOptions(newSize2, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage2!
    }
}

但该函数采用CGSize大小参数(宽度和高度),但我只想得到一个采用width参数的函数。

如何编辑我的代码来解决我的问题?
任何帮助都将非常感谢:)

注意:UIImage应该获得更小的分辨率(更少的像素),而不是图像视图本身!

2 个答案:

答案 0 :(得分:3)

您可以根据图像的宽度和宽高比计算所需的高度。同样可以应用于高度参数。以下是UIImage

的扩展示例
extension UIImage {
func resize(width: CGFloat) -> UIImage {
    let height = (width/self.size.width)*self.size.height
    return self.resize(size: CGSize(width: width, height: height))
}

func resize(height: CGFloat) -> UIImage {
    let width = (height/self.size.height)*self.size.width
    return self.resize(size: CGSize(width: width, height: height))
}

func resize(size: CGSize) -> UIImage {
    let widthRatio  = size.width/self.size.width
    let heightRatio = size.height/self.size.height
    var updateSize = size
    if(widthRatio > heightRatio) {
        updateSize = CGSize(width:self.size.width*heightRatio, height:self.size.height*heightRatio)
    } else if heightRatio > widthRatio {
        updateSize = CGSize(width:self.size.width*widthRatio,  height:self.size.height*widthRatio)
    }
    UIGraphicsBeginImageContextWithOptions(updateSize, false, UIScreen.main.scale)
    self.draw(in: CGRect(origin: .zero, size: updateSize))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

}

答案 1 :(得分:1)

对于Swift 4和Swift 3使用低于UIImage扩展名来调整图像大小。根据给定的宽度计算高度。

extension UIImage {
    func resized(toWidth width: CGFloat) -> UIImage? {
        let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
        UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: canvasSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}