Cropping an UIImage

后端 未结 24 1806
轮回少年
轮回少年 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:20

    Swift 5:

    extension UIImage {
        func cropped(rect: CGRect) -> UIImage? {
            guard let cgImage = cgImage else { return nil }
    
            UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
            let context = UIGraphicsGetCurrentContext()
    
            context?.translateBy(x: 0.0, y: self.size.height)
            context?.scaleBy(x: 1.0, y: -1.0)
            context?.draw(cgImage, in: CGRect(x: rect.minX, y: rect.minY, width: self.size.width, height: self.size.height), byTiling: false)
    
    
            let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return croppedImage
        }
    }
    

提交回复
热议问题