Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeverwinterMoon/62287f2ef204aca5e6ae7649e63a1b55 to your computer and use it in GitHub Desktop.
Save NeverwinterMoon/62287f2ef204aca5e6ae7649e63a1b55 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