UIImage: Resize, then Crop

后端 未结 16 2435
夕颜
夕颜 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:33

    Here is a Swift 3 version of Sam Wirch's guide to swift posted by William T.

    extension UIImage {
    
        static func resizedCroppedImage(image: UIImage, newSize:CGSize) -> UIImage? {
            var ratio: CGFloat = 0
            var delta: CGFloat = 0
            var offset = CGPoint.zero
    
            if image.size.width > image.size.height {
                ratio = newSize.width / image.size.width
                delta = (ratio * image.size.width) - (ratio * image.size.height)
                offset = CGPoint(x: delta / 2, y: 0)
            } else {
                ratio = newSize.width / image.size.height
                delta = (ratio * image.size.height) - (ratio * image.size.width)
                offset = CGPoint(x: 0, y: delta / 2)
            }
    
            let clipRect = CGRect(x: -offset.x, y: -offset.y, width: (ratio * image.size.width) + delta, height: (ratio * image.size.height) + delta)
            UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
            UIRectClip(clipRect)
            image.draw(in: clipRect)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return newImage
        }
    
    }
    

提交回复
热议问题