UIImage: Resize, then Crop

后端 未结 16 2287
夕颜
夕颜 2020-11-22 11:51

I\'ve been bashing my face into this one for literally days now and even though I feel constantly that I am right on the edge of revelation, I simply cannot achieve my goal.

16条回答
  •  悲哀的现实
    2020-11-22 12:24

    This is a version of Jane Sales' answer in Swift. Cheers!

    public func resizeImage(image: UIImage, size: CGSize) -> UIImage? {
        var returnImage: UIImage?
    
        var scaleFactor: CGFloat = 1.0
        var scaledWidth = size.width
        var scaledHeight = size.height
        var thumbnailPoint = CGPointMake(0, 0)
    
        if !CGSizeEqualToSize(image.size, size) {
            let widthFactor = size.width / image.size.width
            let heightFactor = size.height / image.size.height
    
            if widthFactor > heightFactor {
                scaleFactor = widthFactor
            } else {
                scaleFactor = heightFactor
            }
    
            scaledWidth = image.size.width * scaleFactor
            scaledHeight = image.size.height * scaleFactor
    
            if widthFactor > heightFactor {
                thumbnailPoint.y = (size.height - scaledHeight) * 0.5
            } else if widthFactor < heightFactor {
                thumbnailPoint.x = (size.width - scaledWidth) * 0.5
            }
        }
    
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
    
        var thumbnailRect = CGRectZero
        thumbnailRect.origin = thumbnailPoint
        thumbnailRect.size.width = scaledWidth
        thumbnailRect.size.height = scaledHeight
    
        image.drawInRect(thumbnailRect)
        returnImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return returnImage
    }
    

提交回复
热议问题