The simplest way to resize an UIImage?

前端 未结 30 2579
迷失自我
迷失自我 2020-11-21 22:38

In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

UIImage *newI         


        
30条回答
  •  隐瞒了意图╮
    2020-11-21 22:59

    Swift solution for Stretch Fill, Aspect Fill and Aspect Fit

    extension UIImage {
        enum ContentMode {
            case contentFill
            case contentAspectFill
            case contentAspectFit
        }
        
        func resize(withSize size: CGSize, contentMode: ContentMode = .contentAspectFill) -> UIImage? {
            let aspectWidth = size.width / self.size.width
            let aspectHeight = size.height / self.size.height
            
            switch contentMode {
            case .contentFill:
                return resize(withSize: size)
            case .contentAspectFit:
                let aspectRatio = min(aspectWidth, aspectHeight)
                return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
            case .contentAspectFill:
                let aspectRatio = max(aspectWidth, aspectHeight)
                return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
            }
        }
        
        private func resize(withSize size: CGSize) -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
            defer { UIGraphicsEndImageContext() }
            draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    

    and to use you can do the following:

    let image = UIImage(named: "image.png")!
    let newImage = image.resize(withSize: CGSize(width: 200, height: 150), contentMode: .contentAspectFill)
    

    Thanks to abdullahselek for his original solution.

提交回复
热议问题