Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Created April 10, 2018 05:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save brownsoo/1b772612b54c4dc58d88ae71aec19552 to your computer and use it in GitHub Desktop.
Save brownsoo/1b772612b54c4dc58d88ae71aec19552 to your computer and use it in GitHub Desktop.
Cut UIImage with rounded rectangle or circle
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