The simplest way to resize an UIImage?

前端 未结 30 2601
迷失自我
迷失自我 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条回答
  •  -上瘾入骨i
    2020-11-21 22:55

    Here my somewhat-verbose Swift code

    func scaleImage(image:UIImage,  toSize:CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(toSize, false, 0.0);
    
        let aspectRatioAwareSize = self.aspectRatioAwareSize(image.size, boxSize: toSize, useLetterBox: false)
    
    
        let leftMargin = (toSize.width - aspectRatioAwareSize.width) * 0.5
        let topMargin = (toSize.height - aspectRatioAwareSize.height) * 0.5
    
    
        image.drawInRect(CGRectMake(leftMargin, topMargin, aspectRatioAwareSize.width , aspectRatioAwareSize.height))
        let retVal = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return retVal
    }
    
    func aspectRatioAwareSize(imageSize: CGSize, boxSize: CGSize, useLetterBox: Bool) -> CGSize {
        // aspect ratio aware size
        // http://stackoverflow.com/a/6565988/8047
        let imageWidth = imageSize.width
        let imageHeight = imageSize.height
        let containerWidth = boxSize.width
        let containerHeight = boxSize.height
    
        let imageAspectRatio = imageWidth/imageHeight
        let containerAspectRatio = containerWidth/containerHeight
    
        let retVal : CGSize
        // use the else at your own risk: it seems to work, but I don't know 
        // the math
        if (useLetterBox) {
            retVal = containerAspectRatio > imageAspectRatio ? CGSizeMake(imageWidth * containerHeight / imageHeight, containerHeight) : CGSizeMake(containerWidth, imageHeight * containerWidth / imageWidth)
        } else {
            retVal = containerAspectRatio < imageAspectRatio ? CGSizeMake(imageWidth * containerHeight / imageHeight, containerHeight) : CGSizeMake(containerWidth, imageHeight * containerWidth / imageWidth)
        }
    
        return retVal
    }
    

提交回复
热议问题