Created
April 10, 2018 05:52
-
-
Save brownsoo/1b772612b54c4dc58d88ae71aec19552 to your computer and use it in GitHub Desktop.
Cut UIImage with rounded rectangle or circle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension UIImage { | |
func round(_ radius: CGFloat) -> UIImage { | |
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) | |
let renderer = UIGraphicsImageRenderer(size: rect.size) | |
let result = renderer.image { c in | |
let rounded = UIBezierPath(roundedRect: rect, cornerRadius: radius) | |
rounded.addClip() | |
if let cgImage = self.cgImage { | |
UIImage(cgImage: cgImage, scale: self.scale, orientation: self.imageOrientation).draw(in: rect) | |
} | |
} | |
return result | |
} | |
func circle() -> UIImage { | |
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) | |
let renderer = UIGraphicsImageRenderer(size: rect.size) | |
let result = renderer.image { c in | |
let isPortrait = size.height > size.width | |
let isLandscape = size.width > size.height | |
let breadth = min(size.width, size.height) | |
let breadthSize = CGSize(width: breadth, height: breadth) | |
let breadthRect = CGRect(origin: .zero, size: breadthSize) | |
let origin = CGPoint(x: isLandscape ? floor((size.width - size.height) / 2) : 0, | |
y: isPortrait ? floor((size.height - size.width) / 2) : 0) | |
let circle = UIBezierPath(ovalIn: breadthRect) | |
circle.addClip() | |
if let cgImage = self.cgImage?.cropping(to: CGRect(origin: origin, size: breadthSize)) { | |
UIImage(cgImage: cgImage, scale: self.scale, orientation: self.imageOrientation).draw(in: rect) | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment