Cropping an UIImage

后端 未结 24 1796
轮回少年
轮回少年 2020-11-22 02:45

I\'ve got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square repre

24条回答
  •  伪装坚强ぢ
    2020-11-22 03:34

    Swift version of awolf's answer, which worked for me:

    public extension UIImage {
        func croppedImage(inRect rect: CGRect) -> UIImage {
            let rad: (Double) -> CGFloat = { deg in
                return CGFloat(deg / 180.0 * .pi)
            }
            var rectTransform: CGAffineTransform
            switch imageOrientation {
            case .left:
                let rotation = CGAffineTransform(rotationAngle: rad(90))
                rectTransform = rotation.translatedBy(x: 0, y: -size.height)
            case .right:
                let rotation = CGAffineTransform(rotationAngle: rad(-90))
                rectTransform = rotation.translatedBy(x: -size.width, y: 0)
            case .down:
                let rotation = CGAffineTransform(rotationAngle: rad(-180))
                rectTransform = rotation.translatedBy(x: -size.width, y: -size.height)
            default:
                rectTransform = .identity
            }
            rectTransform = rectTransform.scaledBy(x: scale, y: scale)
            let transformedRect = rect.applying(rectTransform)
            let imageRef = cgImage!.cropping(to: transformedRect)!
            let result = UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
            return result
        }
    }
    

提交回复
热议问题