如何调整图像大小使其最大宽度为1280px

问题描述 投票:0回答:1

在 SwiftUI AlamoFire 中将图像上传到服务器之前,如何调整图像大小以使其最大宽度为 1280px,同时保持宽高比。

func resizeImage(image: UIImage, maxWidth: CGFloat) -> UIImage? {
    let oldWidth = image.size.width
    let oldHeight = image.size.height

    let scaleFactor = maxWidth / oldWidth
    let newHeight = oldHeight * scaleFactor
    let newWidth = oldWidth * scaleFactor

    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

我想在上传到服务器之前调整图像大小

swiftui uiimage
1个回答
0
投票

我们需要确定比例和大小,然后使用

UIGraphicsImageRenderer
来渲染图像:

extension UIImage {
    func scaled(toWidth: CGFloat) -> UIImage? {
        let scale = toWidth / size.width
        let newHeight = size.height * scale
        let size = CGSize(width: toWidth, height: newHeight)
        let rect = CGRect(origin: .zero, size: size)
        let format = UIGraphicsImageRendererFormat()
        format.scale = self.scale
        return UIGraphicsImageRenderer(size: size, format: format).image { _ in
            draw(in: rect)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.