Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut a UIImage into a circle

Tags:

ios

swift

uiimage

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 UIImageView, then modifying that and displaying it, but you cant set the image of an annotation to an UIImageView, only a UIImage. How should I go about this?

like image 853
Learnin Avatar asked Mar 14 '15 07:03

Learnin


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


2 Answers

Xcode 11 • Swift 5.1 or later

edit/update: For iOS10+ We can use UIGraphicsImageRenderer. For older Swift syntax check edit history.

extension UIImage {     var isPortrait:  Bool    { size.height > size.width }     var isLandscape: Bool    { size.width > size.height }     var breadth:     CGFloat { min(size.width, size.height) }     var breadthSize: CGSize  { .init(width: breadth, height: breadth) }     var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }     var circleMasked: UIImage? {         guard let cgImage = cgImage?             .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,                                               y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),                                 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: .init(origin: .zero, size: breadthSize))         }     } } 

Playground Testing

let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))! profilePicture.circleMasked 

like image 55
Leo Dabus Avatar answered Oct 04 '22 10:10

Leo Dabus


Make sure to import QuarzCore if needed.

 func maskRoundedImage(image: UIImage, radius: CGFloat) -> UIImage {         let imageView: UIImageView = UIImageView(image: image)         let layer = imageView.layer         layer.masksToBounds = true         layer.cornerRadius = radius         UIGraphicsBeginImageContext(imageView.bounds.size)         layer.render(in: UIGraphicsGetCurrentContext()!)         let roundedImage = UIGraphicsGetImageFromCurrentImageContext()         UIGraphicsEndImageContext()         return roundedImage!     } 
like image 36
Nikos M. Avatar answered Oct 04 '22 10:10

Nikos M.