The simplest way to resize an UIImage?

前端 未结 30 3192
迷失自我
迷失自我 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:56

    Here's a Swift version of Paul Lynch's answer

    func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
        image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    

    And as an extension:

    public extension UIImage {
        func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
            // In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
            // Pass 1 to force exact pixel size.
            UIGraphicsBeginImageContextWithOptions(
                /* size: */ newSize,
                /* opaque: */ false,
                /* scale: */ retina ? 0 : 1
            )
            defer { UIGraphicsEndImageContext() }
    
            self.draw(in: CGRect(origin: .zero, size: newSize))
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    

提交回复
热议问题