Cut a UIImage into a circle

后端 未结 11 2304
面向向阳花
面向向阳花 2020-11-27 13:30

I want to cut a UIImage into a circle so that I can then use it as an annotation. Every answer on this site that I\'ve found describes creating an UIImage

11条回答
  •  伪装坚强ぢ
    2020-11-27 14:01

    Swift 5.3, Xcode 12.2, Handles all imageOrientations

    Based on answer Leo Dabus

    Thanks, works perfectly! BUT only for images with imageOrientation .up or .down. For images with .right or .left orientation there are distortions in result. And from iPhone/iPad camera for original photos initially we get .right orientation.

    Code below takes into account imageOrientation property:

    extension UIImage {
    
        func cropToCircle() -> UIImage? {
        
            let isLandscape = size.width > size.height
            let isUpOrDownImageOrientation = [0,1,4,5].contains(imageOrientation.rawValue)
        
            let breadth: CGFloat = min(size.width, size.height)
            let breadthSize = CGSize(width: breadth, height: breadth)
            let breadthRect = CGRect(origin: .zero, size: breadthSize)
        
            let xOriginPoint = CGFloat(isLandscape ?
                                    (isUpOrDownImageOrientation ? ((size.width-size.height)/2).rounded(.down) : 0) :
                                    (isUpOrDownImageOrientation ? 0 : ((size.height-size.width)/2).rounded(.down)))
            let yOriginPoint = CGFloat(isLandscape ?
                                    (isUpOrDownImageOrientation ? 0 : ((size.width-size.height)/2).rounded(.down)) :
                                    (isUpOrDownImageOrientation ? ((size.height-size.width)/2).rounded(.down) : 0))
        
            guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: xOriginPoint, y: yOriginPoint),
                                                         size: breadthSize)) else { return nil }
            let format = imageRendererFormat
            format.opaque = false
        
            return UIGraphicsImageRenderer(size: breadthSize, format: format).image {_ in
                UIBezierPath(ovalIn: breadthRect).addClip()
                UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation).draw(in: CGRect(origin: .zero, size: breadthSize))
            }
        }
    }
    

提交回复
热议问题